package com.bdult.vh.controller;

import java.io.UnsupportedEncodingException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import lgdacom.XPayClient.XPayClient;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.json.simple.JSONValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.bdult.vh.common.CommonUtil;
import com.bdult.vh.common.UtilBean;
import com.bdult.vh.service.CommonService;
import com.bdult.vh.service.ItemService;
import com.bdult.vh.service.OrderService;
import com.bdult.vh.service.MemberService;

/**
 * Handles requests for the application home page.
 */
@Controller
public class OrderController {
	
	private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
	
	@Autowired
	private ItemService itemService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private MemberService memberService;
	
	@RequestMapping(value="cartReg")
	public ModelAndView cartReg(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		String member_id = (String) request.getSession().getAttribute("member_id");
	System.out.println("member_id = " + request.getSession().getAttribute("member_id"));
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		if(member_id==null) {
			//게스트 생성
			//cstmno = CommonUtil.getCreateGuest(request);
		} 
		mv.addObject("cartlist", orderService.getCartList(cstmno));
		mv.addObject("cartCalc", orderService.cartCalc(cstmno));
		
		mv.setViewName("cart");
		return mv;
	}
	
	@RequestMapping(value="delCart")
	public String delCart(@RequestParam("seq_no")String seq_no, HttpServletRequest request) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("seq_no", seq_no);
		String member_id = (String) request.getSession().getAttribute("member_id");
		if(member_id==null) member_id = CommonUtil.getCreateGuest(request);
		map.put("member_id", member_id);
		int result = orderService.delCart(map);
		return "redirect:/cart.vh";
	}
	
	@RequestMapping(value="cart")
	public ModelAndView cart(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		
		//DB에서 장바구니 상품리스트를 뽑아온다
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		paramMap.put("cstmno", Long.valueOf(cstmno).longValue());
		
		HashMap<String,Object> cartList = new HashMap<String,Object>();
		cartList = orderService.getCartList(cstmno);
		String cart_list = "[]";
		if(cartList != null ) {
			cart_list = (String)cartList.get("CARTLIST");
		}
		System.out.println("cart_list = " + cart_list);
		
		JSONArray jsonArray = JSONArray.fromObject(cart_list);
		System.out.println("jsonArray = " + jsonArray.size());
		
		ArrayList<HashMap<String, Object>> itemList_temp = new ArrayList<HashMap<String,Object>>();
		for(int i=0; i<jsonArray.size();i++) {
			JSONObject jSonObject = (JSONObject) jsonArray.get(i);
			String aa = (String) jSonObject.get("a");
			String aaa[] = aa.split("_");
			
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("prdcd", aaa[0]);
			map.put("sapcd", aaa[1]);
			map.put("buyqty", jSonObject.get("b"));
			
			itemList_temp.add( map );
		}		
	logger.info(itemList_temp.toString());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("prdlist", itemList_temp);
		
		//장바구니 상품리스트로 상품정보를 가져온다. 
		int totalCnt = 0;
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		System.out.println("map = " + map + " / " + map.get("prdlist") );
		
		if(! map.get("prdlist").toString().equals("[]") ) {		
			itemList = itemService.getItemList_prdlist(map);
			System.out.println("-- itemList = " + itemList);
			for(HashMap<String,String> item : itemList) {
				String prdimg1 = item.get("PRDIMG1");
				prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
				item.put("PRDIMG1_ENC", prdimg1);
				
				//주문갯수 찾기
				for(HashMap<String,Object> m : itemList_temp) {
					if(m.get("prdcd").equals(item.get("PRDCD"))) {
						item.put("BUYQTY", m.get("buyqty").toString() );
					}
				}
				
				totalCnt++;
			}
		}
		
		mv.addObject("itemList", itemList);
		mv.addObject("totcnt", totalCnt);
		
		mv.setViewName("cart");
		return mv;
	}
	
	@RequestMapping(value="cart_guest")
	public ModelAndView cart_guest(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		int totalCnt = 0;
		
		String cc = "[]";
		int k = 0;
		Cookie[] cookies = request.getCookies();
		for(Cookie val : cookies) {
			String name  = val.getName();
			String value  = val.getValue();
			System.out.println(k++ + ".COOKIES NAME : " + name + " / VALUE : " + value);
			if(name.equals("cartList")) {
				cc = value;
			}
		}
		
		if(!cc.equals("[]") && !cc.equals("%5B%5D")) {
			JSONArray jsonArray = JSONArray.fromObject(cc);
			System.out.println("jsonArray = " + jsonArray.size());
			
			ArrayList<HashMap<String, Object>> itemList_temp = new ArrayList<HashMap<String,Object>>();
			for(int i=0; i<jsonArray.size();i++) {
				JSONObject jSonObject = (JSONObject) jsonArray.get(i);
				String aa = (String) jSonObject.get("a");
				String aaa[] = aa.split("_");
				
				HashMap<String, Object> map = new HashMap<String,Object>();
				map.put("prdcd", aaa[0]);
				map.put("sapcd", aaa[1]);
				map.put("buyqty", jSonObject.get("b"));
				
				itemList_temp.add( map );
			}		
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("prdlist", itemList_temp);
			
			//장바구니 상품리스트로 상품정보를 가져온다. 
			itemList = itemService.getItemList_prdlist(map);
			System.out.println("-- itemList = " + itemList);
			for(HashMap<String,String> item : itemList) {
				String prdimg1 = item.get("PRDIMG1");
				prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
				item.put("PRDIMG1_ENC", prdimg1);
				
				//주문갯수 찾기
				for(HashMap<String,Object> m : itemList_temp) {
					if(m.get("prdcd").equals(item.get("PRDCD"))) {
						item.put("BUYQTY", m.get("buyqty").toString() );
					}
				}
				
				totalCnt++;
			}
		}
		
		mv.addObject("itemList", itemList);
		mv.addObject("totcnt", totalCnt);
		
		mv.setViewName("cart_guest");
		return mv;
	}
	
	@RequestMapping(value="order")
	public ModelAndView order(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();

		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		String member_id = (String) request.getSession().getAttribute("member_id");
		
		if(member_id==null) {
			mv.addObject("rsltmsg","주문에서 오류가 발생하였습니다.");
			mv.setViewName("redirect:/main.vh");
			return mv;
			
		}
		paramMap.put("cstmno", Long.valueOf(cstmno).longValue());
		HashMap<String,Object> cartList = new HashMap<String,Object>();
		
		//장바구니 구매인지 바로구매인지 판단한다
		System.out.println("**** paramMap in order.vh : " + paramMap);
		String mode = "cart";
		if(paramMap.get("mode")!=null) {
			if(paramMap.get("mode").toString().equals("direct")) {
				mode="direct";
			}
		} 
		
		if(mode.equals("cart")) {
			cartList = orderService.getCartList(cstmno);
		} else {
			cartList = orderService.getCartOrderList(cstmno);
		}
		
		String cc = "[]";
		int k = 0;
		Cookie[] cookies = request.getCookies();
		for(Cookie val : cookies) {
			String name  = val.getName();
			String value  = val.getValue();
			System.out.println(k++ + ".COOKIES NAME : " + name + " / VALUE : " + value);
			if(name.equals("orderList")) {
				System.out.println(k++ + ".COOKIES NAME======== : " + name + " / VALUE : " + value);
				cc = value;
			}
		}
		
	
		if(!cc.equals("[]") && !cc.equals("%5B%5D")) {
		}else{
			cc = (String)cartList.get("CARTLIST");
		}

		
		JSONArray jsonArray = JSONArray.fromObject(cc);
		System.out.println("jsonArray.size() = " + jsonArray.size() + " / jsonArray = " + jsonArray);
		
		ArrayList<HashMap<String, Object>> itemList_temp = new ArrayList<HashMap<String,Object>>();
		for(int i=0; i<jsonArray.size();i++) {
			JSONObject jSonObject = (JSONObject) jsonArray.get(i);
			String aa = (String) jSonObject.get("a");
			String aaa[] = aa.split("_");
			
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("prdcd", aaa[0]);
			map.put("sapcd", aaa[1]);
			map.put("buyqty", jSonObject.get("b"));
			
			itemList_temp.add( map );
		}		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("prdlist", itemList_temp);
		
		//장바구니 상품리스트로 상품정보를 가져온다. 
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		itemList = itemService.getItemList_prdlist(map);
		int totalCnt = 0;
		int totalPrc = 0;
		int totalCpnPrc = 0;
		int dlvmspol = 0;
		int dlvmsimpoprc = 0;
		int dlvmsfsprc = 0;
		String pdtNm = "";
		int pdtCnt = 0;
		int buy_qty = 1;
		for(HashMap<String,String> item : itemList) {
			System.out.println("-- item = " + item);
			String prdimg1 = item.get("PRDIMG1");
			prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
			item.put("PRDIMG1_ENC", prdimg1);
			
			//주문갯수 찾기
			for(HashMap<String,Object> m : itemList_temp) {
				if(m.get("prdcd").equals(item.get("PRDCD"))) {
					item.put("BUYQTY", m.get("buyqty").toString() );
					buy_qty = Integer.parseInt( m.get("buyqty").toString() );
				}
			}
			
			
			totalCnt++;
			//### 2014-05-01 심윤 추가 : 회원정보 호출, 과거배송지, 배송비처리
			int selPrc = Integer.parseInt(String.valueOf(item.get("SELPRC")));
			int cpnPrc = Integer.parseInt(String.valueOf(item.get("CPNPRC")));
			
			int dlvmsPrc = Integer.parseInt(String.valueOf(item.get("DLVMSPOL")));
			int dlvmsmPrc = Integer.parseInt(String.valueOf(item.get("DLVMSIMPOPRC")));
			int dlvmsfPrc = 0;
			if(item.get("DLVMSFSPRC") != null) dlvmsfPrc = Integer.parseInt(String.valueOf(item.get("DLVMSFSPRC")));
			
			totalPrc += selPrc * buy_qty;
			totalCpnPrc += cpnPrc * buy_qty;
			

			if(dlvmspol == 1) dlvmspol = 1;
			else if(dlvmsPrc == 1) dlvmspol = 1;
			else dlvmspol = dlvmsPrc;			
			if(dlvmsmPrc > dlvmsimpoprc) dlvmsimpoprc = dlvmsmPrc;
			if(dlvmsfPrc > dlvmsfsprc) dlvmsfsprc = dlvmsfPrc;
			
			if(pdtNm.equals("")){
				pdtNm = String.valueOf(item.get("PRDNM"));
			}else{
				pdtCnt++;
			}
			//### 2014-05-01 심윤 추가 : 배송비처리

		}
		//System.out.println("dlvmspol = " + dlvmspol);
		//System.out.println("dlvmsimpoprc = " + dlvmsimpoprc);
		//System.out.println("dlvmsfsprc = " + dlvmsfsprc);
		
		mv.addObject("itemList", itemList);
		mv.addObject("totcnt", totalCnt);
		
		
		//### 2014-05-01 심윤 추가 : 회원정보 호출, 과거배송지, 배송비처리
		mv.addObject("totprc", totalPrc);					//주문금액
		mv.addObject("totcprc", totalCpnPrc);				//할인금액
		mv.addObject("totamt", (totalPrc - totalCpnPrc));	//총 결제금액
		
		if(pdtCnt > 0)
			mv.addObject("pdtNm", pdtNm+" 외 "+pdtCnt+"개 상품");	//제품명
		else
			mv.addObject("pdtNm", pdtNm);					//제품명
		
		mv.addObject("dlvmspol", dlvmspol);					//배송비 구분
		mv.addObject("dlvmsimpoprc", dlvmsimpoprc);			//특정가격이상 배송비
		mv.addObject("dlvmsfsprc", dlvmsfsprc);				//배송비
		
		Map<String, Object> memList = new HashMap<String, Object>();
		memList = memberService.getMemberView(member_id);		
		mv.addObject("memList", memList);
		
		Map<String, Object> pastORDList = new HashMap<String, Object>();
		pastORDList = orderService.getAddressPastOrder(cstmno);
		mv.addObject("pastORDList", pastORDList);
		//### 2014-05-01 심윤 추가 : 회원정보 호출, 과거배송지, 배송비처리
		
		int nPrdCount = 1;
		mv.addObject("nPrdCount", nPrdCount);
		
		mv.setViewName("order");
		return mv;
	}
	
	@RequestMapping(value="order_guest")
	public ModelAndView order_guest(Model model, HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView();
		ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
		int totalCnt = 0;
		
		String cc = "[]";
		int k = 0;
		Cookie[] cookies = request.getCookies();
		for(Cookie val : cookies) {
			String name  = val.getName();
			String value  = val.getValue();
			System.out.println(k++ + ".COOKIES NAME : " + name + " / VALUE : " + value);
			if(name.equals("orderList")) {
				cc = value;
			}
		}
		
		if(!cc.equals("[]") && !cc.equals("%5B%5D")) {
			JSONArray jsonArray = JSONArray.fromObject(cc);
			System.out.println("jsonArray = " + jsonArray.size());
			
			ArrayList<HashMap<String, Object>> itemList_temp = new ArrayList<HashMap<String,Object>>();
			for(int i=0; i<jsonArray.size();i++) {
				JSONObject jSonObject = (JSONObject) jsonArray.get(i);
				String aa = (String) jSonObject.get("a");
				String aaa[] = aa.split("_");
				
				HashMap<String, Object> map = new HashMap<String,Object>();
				map.put("prdcd", aaa[0]);
				map.put("sapcd", aaa[1]);
				map.put("buyqty", jSonObject.get("b"));
				
				itemList_temp.add( map );
			}		
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("prdlist", itemList_temp);
			
			//장바구니 상품리스트로 상품정보를 가져온다. 
			itemList = itemService.getItemList_prdlist(map);
			System.out.println("-- itemList = " + itemList);
			for(HashMap<String,String> item : itemList) {
				String prdimg1 = item.get("PRDIMG1");
				prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
				item.put("PRDIMG1_ENC", prdimg1);
				
				//주문갯수 찾기
				for(HashMap<String,Object> m : itemList_temp) {
					if(m.get("prdcd").equals(item.get("PRDCD"))) {
						item.put("BUYQTY", m.get("buyqty").toString() );
					}
				}
				
				totalCnt++;
			}
		}
		
		mv.addObject("itemList", itemList);
		mv.addObject("totcnt", totalCnt);
		
		mv.setViewName("order_guest");
		return mv;
	}
	
	
	@RequestMapping(value="zipcode")
	public ModelAndView zipcode(HttpServletRequest request, @RequestParam Map<String, Object> paramMap) {
		ModelAndView mv = new ModelAndView();
		
		String dong = request.getParameter("dong");
		if(dong != null){
			if(!dong.equals("")){
				ArrayList<HashMap<String, String>> zipcodeList = new ArrayList<HashMap<String, String>>();
				zipcodeList = orderService.selectZipcodeList(dong);
				mv.addObject("zipcodeList", zipcodeList);
			}
		}
		mv.setViewName("zipcode/zipcode");		
		return mv;
	}
	
	
	@RequestMapping(value="startPG")
	public ModelAndView startPG(HttpServletRequest request, @RequestParam Map<String, Object> paramMap) {
		System.out.println("--- insert startPG");
		HashMap<String, String> map = new HashMap<String, String>();
		String member_id = (String) request.getSession().getAttribute("member_id");
		//if(member_id==null) member_id = BKutil.getCreateGuest(request);
		map.put("member_id", member_id);		
		map.put("bill_select", paramMap.get("bill_select").toString());
		map.put("receive_zipcode1", request.getParameter("receive_zipcode1"));
		map.put("receive_zipcode2", request.getParameter("receive_zipcode2"));
		map.put("receive_address1", request.getParameter("receive_address1"));
		map.put("receive_address2", request.getParameter("receive_address2"));
		map.put("usr_zipcode1", request.getParameter("usr_zipcode1"));
		map.put("usr_zipcode2", request.getParameter("usr_zipcode2"));
		map.put("usr_address1", request.getParameter("usr_address1"));
		map.put("usr_address2", request.getParameter("usr_address2"));
		
		map.put("nPrdCount", request.getParameter("nPrdCount"));
	System.out.println("***** map in startPG : " + map);	
		//map = orderService.insertOrderData(request, map);
		ModelAndView mv = new ModelAndView();
		mv.addObject("payinfo", map);
		
		
		
		//System.out.println("=====================insert startPG"+);
	
		mv.setViewName("pg/lgu/payreq_crossplatform");		
		return mv;
	}
	
	@RequestMapping(value="note_url")
	public ModelAndView note_url(Model model, HttpServletRequest request, @RequestParam Map<String, Object> paramMap) {
		ModelAndView mv = new ModelAndView();
	System.out.println("**** in note_url");
		mv.setViewName("pg/lgu/note_url");	
		return mv;
	}
	
	@RequestMapping(value="Cancel")
	public ModelAndView Cancel(Model model, HttpServletRequest request, @RequestParam Map<String, Object> paramMap) {
		ModelAndView mv = new ModelAndView();
	System.out.println("**** in Cancel");
		mv.setViewName("pg/lgu/Cancel");	
		return mv;
	}
	
	@RequestMapping(value="returnurl")
	public ModelAndView returnurl(Model model, HttpServletRequest request, @RequestParam Map<String, Object> paramMap) {
		ModelAndView mv = new ModelAndView();
	System.out.println("**** in returnurl");
		mv.setViewName("pg/lgu/returnurl");	
		return mv;
	}
	
	@RequestMapping(value="cartAjax")
	public String cartAjax(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		
		String mode = (String)paramMap.get("mode");
		String cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
		System.out.println("mode = " + mode + " / cstmno = " + cstmno );
		if(request.getSession().getAttribute("cstmno") != null) {
			paramMap.put("cstmno", Long.valueOf(cstmno).longValue());
		}
		
		if(mode.equals("get") && request.getSession().getAttribute("cstmno") != null) {
			HashMap<String,Object> cartList = new HashMap<String,Object>();
			cartList = orderService.getCartList(cstmno);
			if(cartList != null) {
				model.addAttribute("cartList", cartList.get("CARTLIST"));
			} else {
				model.addAttribute("cartList", 0);
			}
		} else if(mode.equals("wish") && request.getSession().getAttribute("cstmno") != null) {
			HashMap<String,Object> wishList = new HashMap<String,Object>();
			wishList = orderService.getWishList(cstmno);
			System.out.println("wishList = " + wishList);
			if(wishList != null) {
				model.addAttribute("cartList", wishList.get("WISHLIST"));
			} else {
				model.addAttribute("cartList", 0);
			}
		} else if(mode.equals("insertWish")) {
			System.out.println("paramMap = " + paramMap);
			orderService.insertWish(paramMap);
		} else if(mode.equals("updateWish")) {
			orderService.updateWish(paramMap);
		} else if(mode.equals("insert")) {
			orderService.insertCart(paramMap);
		} else if(mode.equals("update")) {
			System.out.println("********" + paramMap);
			orderService.insertCart(paramMap);
		} else if(mode.equals("update2")) {
			System.out.println("********" + paramMap);
			orderService.insertCart(paramMap);
		} else if(mode.equals("insertOrd")) {
			System.out.println("********" + paramMap);
			orderService.insertCart(paramMap);
		} else if(mode.equals("updateOrd")) {
			System.out.println("********" + paramMap);
			orderService.updateCart(paramMap);
		}
		
		return "jsonView";
	}
	
	@RequestMapping(value="orderNoAjax")
	public String orderNoAjax(Model model, @RequestParam Map<String, Object> paramMap, HttpServletRequest request) {
		String sOrdNo = "";
		
		//주문번호 생성
		try {
		    /********************************************************************************************/
	        /** 주문번호생성(YYYYMMDD + 시퀀스-7자리) **/
	        /********************************************************************************************/
	        SimpleDateFormat dFormat = new SimpleDateFormat("yyyyMMdd");
	        String sDate = dFormat.format(new Date());
	        long iOrdNo = getMaxNumber("TBLORDER.ORDNO", true);
	        System.out.println("--iOrdNo----->" + iOrdNo);
	        sOrdNo = sDate + UtilBean.addZeroFrontOfString(7, UtilBean.checkNullString(iOrdNo));
	      
	        model.addAttribute("ordno", sOrdNo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "jsonView";
	}
	
	/**
	   * tblSequence의 keyID와 일치하는 keyNo의 최대값 +1 반환
	   * 
	   * @param sKeyID : tblSequence의 keyID
	   * @return long
	   * @Author 황세원
	   */
	  private long getMaxNumber(String sKeyID, boolean flag) throws Exception {
		  long iKeyNo = -1;
	    
	      if (flag) {
	    	  
	    	  int iAffected = 0;
	    	  iAffected = commonService.updateSequence(sKeyID);
	    	  if (iAffected <= 0) {
	    		  commonService.insertSequence(sKeyID);
	    	  }
	      }
	      
	      iKeyNo = commonService.selectSequence(sKeyID);;
	      
	      return iKeyNo;
	  }
		
		@RequestMapping(value="payres")
		public ModelAndView payres(Model model, HttpServletRequest request, @RequestParam Map<String, Object> paramMap) {
			ModelAndView mv = new ModelAndView();
			String cstmno = "";
			String cstmrank = "";
			if(request.getSession().getAttribute("cstmno")!=null) {
				cstmno = String.valueOf(request.getSession().getAttribute("cstmno"));
				cstmrank = (String) request.getSession().getAttribute("m_rank");
			}
			System.out.println("####################cstmrank"+cstmrank);
			
        	String member_id = (String) request.getSession().getAttribute("member_id");
        	
		System.out.println("**** in payres");
		
		    /*
		     * [최종결제요청 페이지(STEP2-2)]
		     *
		     * LG유플러스으로 부터 내려받은 LGD_PAYKEY(인증Key)를 가지고 최종 결제요청.(파라미터 전달시 POST를 사용하세요)
		     */
		
			/* ※ 중요
			* 환경설정 파일의 경우 반드시 외부에서 접근이 가능한 경로에 두시면 안됩니다.
			* 해당 환경파일이 외부에 노출이 되는 경우 해킹의 위험이 존재하므로 반드시 외부에서 접근이 불가능한 경로에 두시기 바랍니다. 
			* 예) [Window 계열] C:\inetpub\wwwroot\lgdacom ==> 절대불가(웹 디렉토리)
			*/
			
		    String configPath = "C:/dev/lgdacom";  //로컬 windows
			//String configPath = "/Users/byeong-gug/Documents/lgdacom";  //로컬 Mac
			//String configPath = "/vhmall/lgdacom"; 	 //bdult.com
			//String configPath = "/opt/apache-tomcat-7.0.53/webapps/lgdacom"; 	 //10.10.0.85
		    
		    /*
		     *************************************************
		     * 1.최종결제 요청 - BEGIN
		     *  (단, 최종 금액체크를 원하시는 경우 금액체크 부분 주석을 제거 하시면 됩니다.)
		     *************************************************
		     */
		    String orderno = "";
		    String CST_PLATFORM                 = request.getParameter("CST_PLATFORM");
		    String CST_MID                      = request.getParameter("CST_MID");
		    String LGD_MID                      = ("test".equals(CST_PLATFORM.trim())?"t":"")+CST_MID;
		    String LGD_PAYKEY                   = request.getParameter("LGD_PAYKEY");
		
		    //해당 API를 사용하기 위해 WEB-INF/lib/XPayClient.jar 를 Classpath 로 등록하셔야 합니다. 
		    XPayClient xpay = new XPayClient();
		   	boolean isInitOK = xpay.Init(configPath, CST_PLATFORM);   	
		
		   	if( !isInitOK ) {
		    	//API 초기화 실패 화면처리
		        System.out.println( "결제요청을 초기화 하는데 실패하였습니다.<br>");
		        System.out.println( "LG유플러스에서 제공한 환경파일이 정상적으로 설치 되었는지 확인하시기 바랍니다.<br>");        
		        System.out.println( "mall.conf에는 Mert ID = Mert Key 가 반드시 등록되어 있어야 합니다.<br><br>");
		        System.out.println( "문의전화 LG유플러스 1544-7772<br>");
		        
		        mv.addObject("rsltmsg", "결제요청을 초기화 하는데 실패하였습니다.");
		        mv.setViewName("redirect:/main.vh");
	    		return mv;	   	
		   	}else{      
		   		try{
		   			/*
		   	   	     *************************************************
		   	   	     * 1.최종결제 요청(수정하지 마세요) - END
		   	   	     *************************************************
		   	   	     */
			    	xpay.Init_TX(LGD_MID);
			    	xpay.Set("LGD_TXNAME", "PaymentByKey");
			    	xpay.Set("LGD_PAYKEY", LGD_PAYKEY);
			    
			    	//금액을 체크하시기 원하는 경우 아래 주석을 풀어서 이용하십시요.
			    	//String DB_AMOUNT = "DB나 세션에서 가져온 금액"; //반드시 위변조가 불가능한 곳(DB나 세션)에서 금액을 가져오십시요.
			    	//xpay.Set("LGD_AMOUNTCHECKYN", "Y");
			    	//xpay.Set("LGD_AMOUNT", DB_AMOUNT);
			    
		    	}catch(Exception e) {
		    		System.out.println("LG유플러스 제공 API를 사용할 수 없습니다. 환경파일 설정을 확인해 주시기 바랍니다. ");
		    		System.out.println(""+e.getMessage());    	
		    		
		    		mv.addObject("rsltmsg", "LG유플러스 제공 API를 사용할 수 없습니다");
		    		mv.setViewName("redirect:/main.vh");
		    		return mv;
		    	}
		   	}
		
		    /*
		     * 2. 최종결제 요청 결과처리
		     *
		     * 최종 결제요청 결과 리턴 파라미터는 연동메뉴얼을 참고하시기 바랍니다.
		     */
		     if ( xpay.TX() ) {
		         //1)결제결과 화면처리(성공,실패 결과 처리를 하시기 바랍니다.)
		    	 System.out.println( "결제요청이 완료되었습니다.  <br>");
		    	 System.out.println( "TX 결제요청 Response_code = " + xpay.m_szResCode + "<br>");
		    	 System.out.println( "TX 결제요청 Response_msg = " + xpay.m_szResMsg + "<p>");
		         
		    	 System.out.println("거래번호 : " + xpay.Response("LGD_TID",0) + "<br>");
		    	 System.out.println("상점아이디 : " + xpay.Response("LGD_MID",0) + "<br>");
		    	 System.out.println("상점주문번호 : " + xpay.Response("LGD_OID",0) + "<br>");
		    	 System.out.println("결제금액 : " + xpay.Response("LGD_AMOUNT",0) + "<br>");
		    	 System.out.println("결과코드 : " + xpay.Response("LGD_RESPCODE",0) + "<br>");
		    	 System.out.println("결과메세지 : " + xpay.Response("LGD_RESPMSG",0) + "<p>");
		         
		         for (int i = 0; i < xpay.ResponseNameCount(); i++)
		         {
		        	 System.out.println(xpay.ResponseName(i) + " = ");
		             for (int j = 0; j < xpay.ResponseCount(); j++)
		             {
		            	 System.out.println("\t" + xpay.Response(xpay.ResponseName(i), j) + "<br>");
		             }
		         }
		         System.out.println("<p>");
		         
		         if( "0000".equals( xpay.m_szResCode ) ) {
		         	//최종결제요청 결과 성공 DB처리
		        	// System.out.println("최종결제요청 결과 성공 DB처리하시기 바랍니다.<br>");
		        	 
		        	//##############2014-04-30 심윤 추가: 결제 DB저장
		        	HashMap payReqMaps = new HashMap();
					String ORDNO = ""; // 주문번호 /
					String CLAIMNO = ""; // 클레임번호
					String LGD_RESPCODE = ""; // 응답코드 /
					String LGD_RESPMSG = ""; // 응답메세지
					String LGD_OID = ""; // 주문번호 /
					String LGD_AMOUNT = ""; // 결제금액 /
					String LGD_PAYTYPE = ""; // 결제수단 /
					String LGD_PAYDATE = ""; // 결제일 /
					String LGD_HASHDATA = ""; // 헤쉬데이터
					String LGD_TIMESTAMP = ""; // 타임스탬프
					String LGD_BUYER = ""; // 구매자명
					String LGD_PRODUCTINFO = ""; // 구매내역
					String LGD_BUYERID = ""; // 구매자 아이디
					String LGD_BUYERADDRESS = ""; // 구매자 주소
					String LGD_BUYERPHONE = ""; // 구매자 폰번호
					String LGD_BUYEREMAIL = ""; // 구매자 이메일주소
					String LGD_BUYERSSN = ""; // 구매자 주민등록번호
					String LGD_PRODUCTCODE = ""; // 상품코드
					String LGD_RECEIVER = ""; // 수취인
					String LGD_RECEIVERPHONE = ""; // 수취인 폰번호
					String LGD_DELIVERYINFO = ""; // 배송정보
					String LGD_FINANCECODE = ""; // 결제기관코드
					String LGD_FINANCENAME = ""; // 결제기관명
					String LGD_FINANCEAUTHNUM = ""; // 결제기관승인번호
					String LGD_ESCROWYN = ""; // 에스크로적용여부
					String LGD_CASHRECEIPTNUM = ""; // 현금영수증승인여부
					String LGD_CASHRECEIPTSELFYN = ""; // 현금영수증자진발급제유무
					String LGD_CASHRECEIPTKIND = ""; // 현금영수증종류
					String LGD_CARDNUM = ""; // 신용카드번호
					String LGD_CARDINSTALLMONTH = ""; // 신용카드할부개월
					String LGD_CARDNOINTYN = ""; // 신용카드무이자여부
					String LGD_AFFILIATECODE = ""; // 신용카드제휴코드
					String LGD_CARDGUBUN1 = ""; // 신용카드추가정보1
					String LGD_CARDGUBUN2 = ""; // 신용카드추가정보2
					String LGD_CARDACQUIRER = ""; // 신용카드매입사코드
					String LGD_PCANCELFLAG = ""; // 신용카드부분취소가능여부
					String LGD_PCANCELSTR = ""; // 신용카드부분취소불가능사유
					String LGD_TRANSAMOUNT = ""; // 환율적용금액
					String LGD_EXCHANGERATE = ""; // 적용환율
					String LGD_ACCOUNTNUM = ""; // 가상계좌발급번호
					String LGD_ACCOUNTOWNER = ""; // 계좌주명
					String LGD_PAYER = ""; // 가상계좌입금자명
					String LGD_CASTAMOUNT = ""; // 입금누적금액
					String LGD_CASCAMOUNT = ""; // 현입금금액
					String LGD_CASFLAG = ""; // 거래종류(R:할당,I:입금,C:취소)
					String LGD_CASSEQNO = ""; // 가상계좌일련번호
					String LGD_SAOWNER = ""; // 가상계좌 입금계좌주명
					String LGD_TELNO = ""; // 결제휴대폰번호
					String EMPTYDEPONM = ""; // 무통장 입금자
					String EMPTYCLOSEDT = ""; // 무통장 입금기한
					String EMPTYCASHRECEPT = ""; // 무통장 현금영수증 발행구분
					String EMPTYRECECD = ""; // 무통장 현금영수증 발행방법
					String EMPTYRECENO = ""; // 무통장 현금영수증 번호
					String EMPTYBANKCD = ""; // 무통장 은행코드
					String EMPTYBANKNO = ""; // 무통장 은행계좌번호
					String EMPTYBDNO = ""; // 무통장 은행키
					String PAYFLAG = ""; // 결제구분코드
					String REGID = ""; //LGD_MID
					String LGD_TID = "";
					String CASHRECEIPTYN = "";
					String LGD_REQTYPE = "";//ARS 요청타입 (Create:등록요청, Update:변경, Search:등록번호조회)
					String LGD_CALLBACK = "";//ARS 결제전화번호
					String LGD_RESERVENUMBER = "";//예약번호
		        	String usr_zipcode1 = request.getParameter("usr_zipcode1");
					String usr_zipcode2 = request.getParameter("usr_zipcode2");
					String usr_address1 = request.getParameter("usr_address1");
					String usr_address2 = request.getParameter("usr_address2");
					String usr_cell = request.getParameter("usr_cell");
					String usr_email = LGD_BUYEREMAIL; //request.getParameter("usr_email");
					
					String receive_zipcode1 = request.getParameter("receive_zipcode1");
					String receive_zipcode2 = request.getParameter("receive_zipcode2");
					String receive_address1 = request.getParameter("receive_address1");
					String receive_address2 = request.getParameter("receive_address2");
					String receive_name = request.getParameter("receive_name");
					String receive_cell = request.getParameter("receive_cell");
					String receive_email = request.getParameter("receive_email");
					String receive_memo = request.getParameter("receive_memo");
					
					long SEQ = 0L;
					try{
						SEQ = getMaxNumber("TBLPAY.SEQ", true);
			        } catch (Exception e) {
			 			// TODO Auto-generated catch block
			 			e.printStackTrace();
			 		}

					ORDNO	 				=	xpay.Response("LGD_OID",0);
					if(ORDNO==null) ORDNO = request.getParameter("LGD_OID");
					orderno 				= ORDNO;
					CLAIMNO	 				=	xpay.Response("CLAIMNO",0);
					LGD_RESPCODE			=	xpay.Response("LGD_RESPCODE",0);
					LGD_RESPMSG	 			=	xpay.Response("LGD_RESPMSG",0);
					LGD_MID	 				=	xpay.Response("LGD_MID",0);
					LGD_OID	 				=	xpay.Response("LGD_OID",0);
					if(LGD_OID==null) LGD_OID = request.getParameter("LGD_OID");
					LGD_AMOUNT	 			=	xpay.Response("LGD_AMOUNT",0);
					if(LGD_AMOUNT==null) LGD_AMOUNT = request.getParameter("LGD_AMOUNT");
					LGD_PAYTYPE	 			=	xpay.Response("LGD_PAYTYPE",0);
					if(LGD_PAYTYPE==null) LGD_PAYTYPE = request.getParameter("LGD_CUSTOM_USABLEPAY");
					LGD_PAYDATE	 			=	xpay.Response("LGD_PAYDATE",0);
					LGD_HASHDATA			=	xpay.Response("LGD_HASHDATA",0);
					LGD_TIMESTAMP			=	xpay.Response("LGD_TIMESTAMP",0);
					LGD_BUYER	 			=	xpay.Response("LGD_BUYER",0);
					if(LGD_BUYER==null) LGD_BUYER = request.getParameter("usr_name");
					LGD_PRODUCTINFO			=	xpay.Response("LGD_PRODUCTINFO",0);
					if(LGD_PRODUCTINFO==null) LGD_PRODUCTINFO = request.getParameter("LGD_PRODUCTINFO");
					LGD_BUYERID	 			=	xpay.Response("LGD_BUYERID",0);
					if(LGD_BUYERID==null) LGD_BUYERID = cstmno;
					LGD_BUYERID = cstmno;
					LGD_BUYERADDRESS		=	xpay.Response("LGD_BUYERADDRESS",0);
					if(LGD_BUYERADDRESS==null) LGD_BUYERADDRESS = "["+usr_zipcode1 +"-"+ usr_zipcode2 +"] "+ usr_address1 +" "+ usr_address2;
					LGD_BUYERPHONE	 		=	xpay.Response("LGD_BUYERPHONE",0);
					if(LGD_BUYERPHONE==null) LGD_BUYERPHONE = usr_cell;
					LGD_BUYEREMAIL	 		=	xpay.Response("LGD_BUYEREMAIL",0);
					if(LGD_BUYEREMAIL==null) LGD_BUYEREMAIL = usr_email;
					LGD_BUYERSSN	 		=	xpay.Response("LGD_BUYERSSN",0);
					LGD_PRODUCTCODE	 		=	xpay.Response("LGD_PRODUCTCODE",0);
					LGD_RECEIVER	 		=	xpay.Response("LGD_RECEIVER",0);
					if(LGD_RECEIVER==null) LGD_RECEIVER = receive_name;
					LGD_RECEIVERPHONE		=	xpay.Response("LGD_RECEIVERPHONE",0);
					if(LGD_RECEIVERPHONE==null) LGD_RECEIVERPHONE = receive_cell;
					LGD_DELIVERYINFO		=	xpay.Response("LGD_DELIVERYINFO",0);
					if(LGD_DELIVERYINFO==null) LGD_DELIVERYINFO = "["+receive_zipcode1 +"-"+ receive_zipcode2 +"] "+ receive_address1 +" "+ receive_address2;
					LGD_FINANCECODE	 		=	xpay.Response("LGD_FINANCECODE",0);
					LGD_FINANCENAME	 		=	xpay.Response("LGD_FINANCENAME",0);
					LGD_FINANCEAUTHNUM		=	xpay.Response("LGD_FINANCEAUTHNUM",0);
					LGD_ESCROWYN	 		=	xpay.Response("LGD_ESCROWYN",0);
					LGD_CASHRECEIPTNUM		=	xpay.Response("LGD_CASHRECEIPTNUM",0);
					LGD_CASHRECEIPTSELFYN	=	xpay.Response("LGD_CASHRECEIPTSELFYN",0);
					LGD_CASHRECEIPTKIND	 	=	xpay.Response("LGD_CASHRECEIPTKIND",0);
					LGD_CARDNUM	 			=	xpay.Response("LGD_CARDNUM",0);
					LGD_CARDINSTALLMONTH	=	xpay.Response("LGD_CARDINSTALLMONTH",0);
					LGD_CARDNOINTYN	 		=	xpay.Response("LGD_CARDNOINTYN",0);
					LGD_AFFILIATECODE	 	=	xpay.Response("LGD_AFFILIATECODE",0);
					LGD_CARDGUBUN1	 		=	xpay.Response("LGD_CARDGUBUN1",0);
					LGD_CARDGUBUN2	 		=	xpay.Response("LGD_CARDGUBUN2",0);
					LGD_CARDACQUIRER	 	=	xpay.Response("LGD_CARDACQUIRER",0);
					LGD_PCANCELFLAG	 		=	xpay.Response("LGD_PCANCELFLAG",0);
					LGD_PCANCELSTR	 		=	xpay.Response("LGD_PCANCELSTR",0);
					LGD_TRANSAMOUNT	 		=	xpay.Response("LGD_TRANSAMOUNT",0);
					LGD_EXCHANGERATE	 	=	xpay.Response("LGD_EXCHANGERATE",0);
					LGD_ACCOUNTNUM	 		=	xpay.Response("LGD_ACCOUNTNUM",0);
					LGD_ACCOUNTOWNER	 	=	xpay.Response("LGD_ACCOUNTOWNER",0);
					LGD_PAYER	 			=	xpay.Response("LGD_PAYER",0);
					LGD_CASTAMOUNT	 		=	xpay.Response("LGD_CASTAMOUNT",0);
					LGD_CASCAMOUNT	 		=	xpay.Response("LGD_CASCAMOUNT",0);
					LGD_CASFLAG	 			=	xpay.Response("LGD_CASFLAG",0);
					LGD_CASSEQNO	 		=	xpay.Response("LGD_CASSEQNO",0);
					LGD_SAOWNER	 			=	xpay.Response("LGD_SAOWNER",0);
					LGD_TELNO	 			=	xpay.Response("LGD_TELNO",0);
					EMPTYDEPONM	 			=	request.getParameter("emptyDepoNm");
					if(EMPTYDEPONM == null)	 EMPTYDEPONM = "";
					EMPTYCLOSEDT	 		=	request.getParameter("emptyCloseDt");
					if(EMPTYCLOSEDT == null)	 EMPTYCLOSEDT = "";
					EMPTYCASHRECEPT	 		=	request.getParameter("emptyCashRecept");
					if(EMPTYCASHRECEPT == null)	 EMPTYCASHRECEPT = "";
					EMPTYRECECD	 			=	request.getParameter("emptyReceCd");
					if(EMPTYRECECD == null)	 EMPTYRECECD = "";
					EMPTYRECENO	 			=	request.getParameter("emptyReceNo");
					if(EMPTYRECENO == null)	 EMPTYRECENO = "";
					EMPTYBANKCD	 			=	request.getParameter("emptyBankCd");
					if(EMPTYBANKCD == null)	 EMPTYBANKCD = "";
					EMPTYBANKNO	 			=	request.getParameter("emptyBankNo");
					if(EMPTYBANKNO == null)	 EMPTYBANKNO = "";
					EMPTYBDNO	 			=	request.getParameter("emptyBdNo");
					if(EMPTYBDNO == null)	 EMPTYBDNO = "";
					PAYFLAG	 				=	request.getParameter("payFlag");
					if(PAYFLAG == null)	 PAYFLAG = "";
					REGID	 				=	cstmno;
					LGD_TID	 				=	xpay.Response("LGD_TID",0);
					CASHRECEIPTYN			=	(LGD_CASHRECEIPTKIND.equals("0") ? "Y" : LGD_CASHRECEIPTKIND).equals("1") ? "Y" : "N";
					LGD_REQTYPE	 			=	xpay.Response("LGD_REQTYPE",0);
					LGD_CALLBACK	 		=	xpay.Response("LGD_CALLBACK",0);
					LGD_RESERVENUMBER	 	=	xpay.Response("LGD_RESERVENUMBER",0);
					if(LGD_CASHRECEIPTKIND.equals("")){
						if(!EMPTYCASHRECEPT.equals("")){
							LGD_CASHRECEIPTKIND = EMPTYCASHRECEPT;
						}
					}
					
					Time ttSttlDt = new java.sql.Time((new Date()).getTime()); // 현재날짜시간생성
					String payFlag = request.getParameter("payFlag"); // 결제방법
					if(payFlag == null) payFlag = "";
					if(LGD_PAYTYPE.equals("SC0060"))		payFlag = "SM04";
					else if(LGD_PAYTYPE.equals("SC0010"))	payFlag = "SM01";
					else if(LGD_PAYTYPE.equals("SC0040"))	payFlag = "SM03";
						
					String sRf = payFlag.equals("SM03") || payFlag.equals("SM06") ? "RF01" : payFlag.equals("SM05") ? "RF01" : "RF02"; // SM03-무통장,SM06-ARS,SM05-가상계좌는 RF01입금대기 나머지는 RF02입금완료 //입금구분
					String sOd = payFlag.equals("SM03") || payFlag.equals("SM06") ? "OD01" : payFlag.equals("SM05") ? "OD01" : "OD02"; // SM03-무통장,SM06-ARS,SM05-가상계좌는 OD01결제대기 나머지는 OD02결제완료 //주문상태
					Time tSttlDt = payFlag.equals("SM03") || payFlag.equals("SM06") ? null : payFlag.equals("SM05") ? null : ttSttlDt; // SM03-무통장,SM06-ARS,SM05-가상계좌는 빈값 나머지는 현재날짜 //결제날짜
					
					String m_di = (String) request.getSession().getAttribute("m_di");			//중복확인키?
					if(m_di == null) m_di = request.getParameter("di");		
					String m_rank = (String) request.getSession().getAttribute("m_rank");		//회원등급
					if(m_rank == null) m_rank = "";
					
					String sMemberNo = cstmno;
					String sUserId = member_id; 						// 회원아디
					String sCstmFl = "MD01";							//회원 구분 (MD01:온라인 회원, MD02:전화회원)
					String sNCstmOrdFl = "MD01";
					if(cstmno.equals(""))	sNCstmOrdFl = "MD03";		//비회원 
					
					String sNCstmPswd = request.getParameter("nCstmPswd"); // 비회원 비밀번호
					String sDi = m_di; // 중복확인키
					String sRank = cstmrank; // 회원등급
					
					String sOrderNm = LGD_BUYER;//request.getParameter("usr_name"); // 주문자 이름
					String sOrdTelNo1 = request.getParameter("ordererTelNo1"); // 주문자 전화1
					if(sOrdTelNo1 == null) sOrdTelNo1 = "";
					String sOrdTelNo2 = request.getParameter("ordererTelNo2"); // 주문자 전화2
					if(sOrdTelNo2 == null) sOrdTelNo2 = "";
					String sOrdTelNo3 = request.getParameter("ordererTelNo3"); // 주문자 전화3
					if(sOrdTelNo3 == null) sOrdTelNo3 = "";
					String sOrdTelNo = usr_cell; //request.getParameter("usr_cell"); //sOrdTelNo2.equals("") ? "" : sOrdTelNo1 + "-" + sOrdTelNo2 + "-" + sOrdTelNo3;
					String sOrdZipcode1 = usr_zipcode1; //request.getParameter("usr_zipcode1"); // 주문자 우편번호1
					if(sOrdZipcode1 == null) sOrdZipcode1 = "";
					String sOrdZipcode2 = usr_zipcode2; //request.getParameter("usr_zipcode2"); // 주문자 우편번호2
					if(sOrdZipcode2 == null) sOrdZipcode2 = "";
					String sOrdZipcode = sOrdZipcode1.equals("") ? "" : sOrdZipcode1 + "-" + sOrdZipcode2;
					String sOrdEmail = usr_email; //request.getParameter("usr_email"); // 주문자 이메일
					String sOrdAddr1 = usr_address1; //request.getParameter("usr_address1"); // 주문자 집주소
					String sOrdAddr2 = usr_address2; //request.getParameter("usr_address2"); // 주문자 집상세주소
										
					String sSederNm = LGD_RECEIVER; //request.getParameter("receive_name"); // 받는이 이름
					String sSedTelNo1 = request.getParameter("sendeeTelNo1"); // 받는이 전화1
					if(sSedTelNo1 == null) sSedTelNo1 = "";
					String sSedTelNo2 = request.getParameter("sendeeTelNo2"); // 받는이 전화2
					if(sSedTelNo2 == null) sSedTelNo2 = "";
					String sSedTelNo3 = request.getParameter("sendeeTelNo3"); // 받는이 전화3
					if(sSedTelNo3 == null) sSedTelNo3 = "";
					String sSedTelNo = receive_cell; //request.getParameter("receive_cell"); //sSedTelNo2.equals("") ? "" : sSedTelNo1 + "-" + sSedTelNo2 + "-" + sSedTelNo3;
					String sSedEmail = receive_email; //request.getParameter("receive_email"); // 받는이 이메일
					String sSedZipcode1 = receive_zipcode1; //request.getParameter("receive_zipcode1"); // 받는이 우편번호1
					if(sSedZipcode1 == null) sSedZipcode1 = "";
					String sSedZipcode2 = receive_zipcode2; //request.getParameter("receive_zipcode2"); // 받는이 우편번호2
					if(sSedZipcode2 == null) sSedZipcode2 = "";
					String sSedZipcode = sSedZipcode1.equals("") ? "" : sSedZipcode1 + "-" + sSedZipcode2;
					String sSedAddr1 = receive_address1; //request.getParameter("receive_address1"); // 받는이 집주소
					String sSedAddr2 = receive_address2; //request.getParameter("receive_address2"); // 받는이 집상세주소
					String sSedMsg = receive_memo; //request.getParameter("receive_memo"); // 받는이 배송메세지

					String sSttlMethod = payFlag;	//request.getParameter("payFlag"); // 결재방법
//					String[] aOrdUseCpnCd = request.getParameterValues("ordUseCpnCd"); // 쿠폰사용코드
//					String[] aOrdDblCpnCd = request.getParameterValues("ordDblCpnCd"); // 더블쿠폰사용코드
					
					//String nPrdTotalFee	= request.getParameter("nPrdTotalFee");					//총 삼품금액
					//String sumCpnPrc = request.getParameter("sumCpnPrc");						//쿠폰사용 금액
					//String nMinusPointTotalFee = request.getParameter("nMinusPointTotalFee");	//사용  포인트
					//String nPlusPoint = request.getParameter("nPlusPoint");						//적립금
					//String nPrdCount = request.getParameter("nPrdCount");						//총 주문 상품개수
					//String sModelPrdNm = request.getParameter("sModelPrdNm");					//대표상품명
					//String nDeliFee = request.getParameter("nDeliFee");							//배송비
					//String sCardRat = request.getParameter("sCardRat");							//카드할인율
					//String nTotCardDcfee = request.getParameter("nTotCardDcfee");				//카드할인금액
					//String sCardTermPrc = request.getParameter("sCardTermPrc");					//카드할인조건 금액
					
					int sumCpnPrc = 0; // 쿠폰사용금액 총합계
				    int sumQty = 0; // 총주문수량
				    String sCpnSeq = "";
				    long iCPNDEDETAILSEQ = 0L;
				    int nPrdCount = 0; // 총 주문 상품 갯수
					int nMinusPointTotalFee = 0; // 사용 포인트
					int nDeliFee = 0; // 배송비용
					int nTotalSettleFee = 0; // 총 결제 금액
					int nPrdTotalFee = 0; // 총 상품 금액
					int nPlusPoint = 0; // 적립 예정 포인트
					int nTotCardDcfee = 0;
					String sModelPrdNm = LGD_PRODUCTINFO; // 대표 상품명
					String sCardCd = "";
					String sCardRat = "";
					String sCardTermPrc = "";
					boolean bComVita = false; // 자사상품 체크
					String sCpnUseYN = request.getParameter("cpnuseyn"); // 쿠폰사용여부
					if(sCpnUseYN == null)	sCpnUseYN = "N";
					String point = request.getParameter("point");
					if(point == null)	point = "0";
					
				    String[] aOrdUseCpnCd = request.getParameterValues("ordUseCpnCd");
				    String[] aOrdDblCpnCd = request.getParameterValues("ordDblCpnCd");
				    
				    
		        	
					payReqMaps.put("SEQ"	, SEQ);
					payReqMaps.put("ORDNO"	, ORDNO);
					payReqMaps.put("CLAIMNO"	, CLAIMNO);
					payReqMaps.put("LGD_RESPCODE"	, LGD_RESPCODE);
					payReqMaps.put("LGD_RESPMSG"	, LGD_RESPMSG);
					payReqMaps.put("LGD_MID"	, LGD_MID);
					payReqMaps.put("LGD_OID"	, LGD_OID);
					payReqMaps.put("LGD_AMOUNT"	, LGD_AMOUNT);
					payReqMaps.put("LGD_PAYTYPE"	, LGD_PAYTYPE);
					payReqMaps.put("LGD_PAYDATE"	, LGD_PAYDATE);
					payReqMaps.put("LGD_HASHDATA"	, LGD_HASHDATA);
					payReqMaps.put("LGD_TIMESTAMP"	, LGD_TIMESTAMP);
					payReqMaps.put("LGD_BUYER"	, LGD_BUYER);
					payReqMaps.put("LGD_PRODUCTINFO"	, LGD_PRODUCTINFO);
					payReqMaps.put("LGD_BUYERID"	, LGD_BUYERID);
					payReqMaps.put("LGD_BUYERADDRESS"	, LGD_BUYERADDRESS);
					payReqMaps.put("LGD_BUYERPHONE"	, LGD_BUYERPHONE);
					payReqMaps.put("LGD_BUYEREMAIL"	, LGD_BUYEREMAIL);
					payReqMaps.put("LGD_BUYERSSN"	, LGD_BUYERSSN);
					payReqMaps.put("LGD_PRODUCTCODE"	, LGD_PRODUCTCODE);
					payReqMaps.put("LGD_RECEIVER"	, LGD_RECEIVER);
					payReqMaps.put("LGD_RECEIVERPHONE"	, LGD_RECEIVERPHONE);
					payReqMaps.put("LGD_DELIVERYINFO"	, LGD_DELIVERYINFO);
					payReqMaps.put("LGD_FINANCECODE"	, LGD_FINANCECODE);
					payReqMaps.put("LGD_FINANCENAME"	, LGD_FINANCENAME);
					payReqMaps.put("LGD_FINANCEAUTHNUM"	, LGD_FINANCEAUTHNUM);
					payReqMaps.put("LGD_ESCROWYN"	, LGD_ESCROWYN);
					payReqMaps.put("LGD_CASHRECEIPTNUM"	, LGD_CASHRECEIPTNUM);
					payReqMaps.put("LGD_CASHRECEIPTSELFYN"	, LGD_CASHRECEIPTSELFYN);
					payReqMaps.put("LGD_CASHRECEIPTKIND"	, LGD_CASHRECEIPTKIND);
					payReqMaps.put("LGD_CARDNUM"	, LGD_CARDNUM);
					payReqMaps.put("LGD_CARDINSTALLMONTH"	, LGD_CARDINSTALLMONTH);
					payReqMaps.put("LGD_CARDNOINTYN"	, LGD_CARDNOINTYN);
					payReqMaps.put("LGD_AFFILIATECODE"	, LGD_AFFILIATECODE);
					payReqMaps.put("LGD_CARDGUBUN1"	, LGD_CARDGUBUN1);
					payReqMaps.put("LGD_CARDGUBUN2"	, LGD_CARDGUBUN2);
					payReqMaps.put("LGD_CARDACQUIRER"	, LGD_CARDACQUIRER);
					payReqMaps.put("LGD_PCANCELFLAG"	, LGD_PCANCELFLAG);
					payReqMaps.put("LGD_PCANCELSTR"	, LGD_PCANCELSTR);
					payReqMaps.put("LGD_TRANSAMOUNT"	, LGD_TRANSAMOUNT);
					payReqMaps.put("LGD_EXCHANGERATE"	, LGD_EXCHANGERATE);
					payReqMaps.put("LGD_ACCOUNTNUM"	, LGD_ACCOUNTNUM);
					payReqMaps.put("LGD_ACCOUNTOWNER"	, LGD_ACCOUNTOWNER);
					payReqMaps.put("LGD_PAYER"	, LGD_PAYER);
					payReqMaps.put("LGD_CASTAMOUNT"	, LGD_CASTAMOUNT);
					payReqMaps.put("LGD_CASCAMOUNT"	, LGD_CASCAMOUNT);
					payReqMaps.put("LGD_CASFLAG"	, LGD_CASFLAG);
					payReqMaps.put("LGD_CASSEQNO"	, LGD_CASSEQNO);
					payReqMaps.put("LGD_SAOWNER"	, LGD_SAOWNER);
					payReqMaps.put("LGD_TELNO"	, LGD_TELNO);
					payReqMaps.put("EMPTYDEPONM"	, EMPTYDEPONM);
					payReqMaps.put("EMPTYCLOSEDT"	, EMPTYCLOSEDT);
					payReqMaps.put("EMPTYCASHRECEPT"	, EMPTYCASHRECEPT);
					payReqMaps.put("EMPTYRECECD"	, EMPTYRECECD);
					payReqMaps.put("EMPTYRECENO"	, EMPTYRECENO);
					payReqMaps.put("EMPTYBANKCD"	, EMPTYBANKCD);
					payReqMaps.put("EMPTYBANKNO"	, EMPTYBANKNO);
					payReqMaps.put("EMPTYBDNO"	, EMPTYBDNO);
					payReqMaps.put("PAYFLAG"	, PAYFLAG);
					payReqMaps.put("REGID"	, REGID);
					payReqMaps.put("LGD_TID"	, LGD_TID);
					payReqMaps.put("CASHRECEIPTYN"	, CASHRECEIPTYN);
					payReqMaps.put("LGD_REQTYPE"	, LGD_REQTYPE);
					payReqMaps.put("LGD_CALLBACK"	, LGD_CALLBACK);
					payReqMaps.put("LGD_RESERVENUMBER"	, LGD_RESERVENUMBER);
					payReqMaps.put("LGD_CASHRECEIPTKIND"	, LGD_CASHRECEIPTKIND);

					boolean isDBOK = true;
					int result = 0;
					if(CASHRECEIPTYN.equals("Y"))
						result = orderService.insertPayCashReceipt(payReqMaps);	// 현금영수증이 발행(Y)이면 발행날짜가 입력된다.
					else
						result = orderService.insertPay(payReqMaps);
					
					if(result == 1){
						ArrayList<HashMap<String, Object>> vList = new ArrayList<HashMap<String, Object>>(); // 상품 리스트
						ArrayList<HashMap<String, Object>> vAccSelPrcList = new ArrayList<HashMap<String, Object>>();
						if(sCpnUseYN == null) sCpnUseYN = "N";
						
						
					    
					    /*
					    System.out.println("=======sCpnUseYN===="+sCpnUseYN);
						System.out.println("=======aOrdUseCpnCd===="+aOrdUseCpnCd);
						System.out.println("=======aOrdDblCpnCd===="+aOrdDblCpnCd);
						System.out.println("=======point===="+point);
						*/
						
						if(sCpnUseYN == null)	sCpnUseYN = "N";
						
						HashMap<String,Object> htReturn = new HashMap<String,Object>();

						HashMap<String,Object> paramMapCart = new HashMap<String,Object>();
						paramMapCart.put("cstmno", Long.valueOf(cstmno).longValue());
						paramMapCart.put("cstmrank", cstmrank);
						paramMapCart.put("sCpnUseYN", sCpnUseYN);
						paramMapCart.put("aOrdUseCpnCd", aOrdUseCpnCd);
						paramMapCart.put("aOrdDblCpnCd", aOrdDblCpnCd);
						paramMapCart.put("point", point);						
						htReturn = getProductCartList(paramMapCart);

						/*
						System.out.println("#################cstmno===="+cstmno);
						System.out.println("#################cstmrank===="+cstmrank);
						System.out.println("#################sCpnUseYN===="+sCpnUseYN);
						System.out.println("#################aOrdUseCpnCd===="+aOrdUseCpnCd);
						System.out.println("#################aOrdDblCpnCd===="+aOrdDblCpnCd);
						System.out.println("#################point===="+point);
						if(true) return mv;
						*/
						
						HashMap<String,Object> htTotalReturn = new HashMap<String,Object>();
						HashMap<String,Object> paramMapht = new HashMap<String,Object>();
						paramMapht.put("cstmno", Long.valueOf(cstmno).longValue());
						paramMapht.put("cstmrank", cstmrank);
						paramMapht.put("sCpnUseYN", sCpnUseYN);
						paramMapht.put("aOrdUseCpnCd", aOrdUseCpnCd);
						paramMapht.put("aOrdDblCpnCd", aOrdDblCpnCd);
						paramMapht.put("point", point);
						htTotalReturn = getAmountCal(paramMapht);

						
						ArrayList<HashMap<String, Object>> vDelifeeList = new ArrayList<HashMap<String, Object>>();
						
						ArrayList<HashMap<String, Object>> htPresentData = new ArrayList<HashMap<String, Object>>();
						HashMap<String,Object> htData = new HashMap<String,Object>();
						if (htReturn != null) {
					      vList = (ArrayList<HashMap<String, Object>>) htReturn.get("vList");
					      sModelPrdNm = UtilBean.checkNullString(htReturn.get("repPrdNm"));
					      htPresentData = (ArrayList<HashMap<String, Object>>) htReturn.get("htPresentData");
					    }
					    if (vList != null && vList.size() > 0) {
					      for (int i = 0; i < vList.size(); i++) {
					        htData = (HashMap<String,Object>) vList.get(i);
					        String sPointYn = UtilBean.checkNullString(htData.get("POINTYN"));
					        String sPrdcd = UtilBean.checkNullString(htData.get("PRDCD"));
					        
					        if (!sPointYn.equals("N")) {
					          //vAccSelPrcList.add(sPrdcd);
					        }
					      }
					    }

					    System.out.println("########### htReturn = " + htReturn);
					    System.out.println("########### vList = " + vList);
						
						if (htTotalReturn != null) {
					      nPrdCount = UtilBean.convertToInt(htTotalReturn.get("nPrdCount"));
					      nDeliFee = UtilBean.convertToInt(htTotalReturn.get("nDeliFee"));
					      nMinusPointTotalFee = UtilBean.convertToInt(htTotalReturn.get("nMinusPointTotalFee"));
					      nTotalSettleFee = UtilBean.convertToInt(htTotalReturn.get("nTotalSettleFee"));
					      nPrdTotalFee = UtilBean.convertToInt(htTotalReturn.get("nPrdTotalFee"));
					      nPlusPoint = UtilBean.convertToInt(htTotalReturn.get("nPlusPoint"));
					      nTotCardDcfee = UtilBean.convertToInt(htTotalReturn.get("nTotCardDcfee"));
					      sCardCd = UtilBean.checkNullString(htTotalReturn.get("sCardCd"));
					      sCardRat = UtilBean.checkNullString(htTotalReturn.get("sCardRat"));
					      sCardTermPrc = UtilBean.checkNullString(htTotalReturn.get("sCardTermPrc"));
					      vDelifeeList = (ArrayList<HashMap<String, Object>>) htTotalReturn.get("vDelifeeList");
					    }
						/********************************************************************************************/
					    /** 사용포인트 적용(차감) **/
					    /********************************************************************************************/
					    if(nMinusPointTotalFee > 0){
					    	try {
								CommonUtil.insertPoint(ORDNO, cstmno, "5", "-", UtilBean.checkNullString(nMinusPointTotalFee), "주문차감", "", "Y", "");
							} catch (Exception e) {
								e.printStackTrace();
							}
					    }
					    
					    

/*
						System.out.println("=======ORDNO===="+LGD_OID);
						System.out.println("=======CSTMID===="+sUserId);
						System.out.println("=======CSTMNO===="+sMemberNo);
						System.out.println("=======NCSTMORDFL===="+sNCstmOrdFl);
						System.out.println("=======NCSTMPSWD===="+sNCstmPswd);
						System.out.println("=======DI===="+sDi);
						System.out.println("=======CSTMGR===="+sRank);
						System.out.println("=======MBLNO===="+sOrdTelNo);
						System.out.println("=======CURORDSTATCD===="+sOd);
						System.out.println("=======DPSTCL===="+sRf);
						System.out.println("=======STTLMETHOD===="+sSttlMethod);
						System.out.println("=======STTLDT===="+tSttlDt);
						System.out.println("=======STTLPRC===="+LGD_AMOUNT);
						System.out.println("=======PRDORDPRC===="+nPrdTotalFee);
						System.out.println("=======USECPNPRC===="+sumCpnPrc);
						System.out.println("=======USECASHPT===="+nMinusPointTotalFee);
						System.out.println("=======TOTACCUMCASHPT===="+nPlusPoint);
						System.out.println("=======PURQTY===="+nPrdCount);
						System.out.println("=======CSTMNM===="+sOrderNm);
						System.out.println("=======ORDMBLNO===="+sOrdTelNo);
						System.out.println("=======CSTMEMAIL===="+sOrdEmail);
						System.out.println("=======ORDZIPCODE===="+sOrdZipcode);
						System.out.println("=======ORDADDR1===="+sOrdAddr1);
						System.out.println("=======ORDADDR2===="+sOrdAddr2);
						System.out.println("=======RECVNM===="+sSederNm);
						System.out.println("=======PHONENO===="+sSedTelNo);
						System.out.println("=======EMAIL===="+sSedEmail);
						System.out.println("=======ZIPCODE===="+sSedZipcode);
						System.out.println("=======DLVADDR1===="+sSedAddr1);
						System.out.println("=======DLVADDR2===="+sSedAddr2);
						System.out.println("=======DLVMSG===="+sSedMsg);
						System.out.println("=======MODELPRDNM===="+sModelPrdNm);
						System.out.println("=======DLVCOST===="+nDeliFee);
						System.out.println("=======USECARDCD===="+LGD_AFFILIATECODE);
						System.out.println("=======USECARDRAT===="+sCardRat);
						System.out.println("=======CARDSALEPRC===="+nTotCardDcfee);
						System.out.println("=======REGID===="+sMemberNo);
						System.out.println("=======CARDTERMPRC===="+sCardTermPrc);
*/
						payReqMaps = new HashMap<String,Object>();
						payReqMaps.put("ORDNO" , LGD_OID);
						payReqMaps.put("CSTMID" , sUserId);
						payReqMaps.put("CSTMNO" , sMemberNo);
						payReqMaps.put("NCSTMORDFL" , sNCstmOrdFl);
						
						payReqMaps.put("NCSTMPSWD" , sNCstmPswd);
						payReqMaps.put("DI" , sDi);
						payReqMaps.put("CSTMGR" , sRank);
						payReqMaps.put("MBLNO" , sOrdTelNo);
						payReqMaps.put("CURORDSTATCD" , sOd);
						
						payReqMaps.put("DPSTCL" , sRf);
						payReqMaps.put("STTLMETHOD" , sSttlMethod);
						
						payReqMaps.put("STTLDT" , tSttlDt);
						
						payReqMaps.put("STTLPRC" , LGD_AMOUNT);
						payReqMaps.put("PRDORDPRC" , nPrdTotalFee);
						payReqMaps.put("USECPNPRC" , sumCpnPrc);
						payReqMaps.put("USECASHPT" , nMinusPointTotalFee);
						payReqMaps.put("TOTACCUMCASHPT" , nPlusPoint);
						
						payReqMaps.put("PURQTY" , nPrdCount);
						payReqMaps.put("CSTMNM" , sOrderNm);
						payReqMaps.put("ORDMBLNO" , sOrdTelNo);
						payReqMaps.put("CSTMEMAIL" , sOrdEmail);
						payReqMaps.put("ORDZIPCODE" , sOrdZipcode);
						
						payReqMaps.put("ORDADDR1" , sOrdAddr1);
						payReqMaps.put("ORDADDR2" , sOrdAddr2);
						payReqMaps.put("RECVNM" , sSederNm);
						payReqMaps.put("PHONENO" , sSedTelNo);
						payReqMaps.put("EMAIL" , sSedEmail);
						
						payReqMaps.put("ZIPCODE" , sSedZipcode);
						payReqMaps.put("DLVADDR1" , sSedAddr1);
						payReqMaps.put("DLVADDR2" , sSedAddr2);
						payReqMaps.put("DLVMSG" , sSedMsg);
						payReqMaps.put("MODELPRDNM" , sModelPrdNm);
						
						payReqMaps.put("DLVCOST" , nDeliFee);
						
						payReqMaps.put("USECARDCD" , LGD_AFFILIATECODE);
						payReqMaps.put("USECARDRAT" , sCardRat);
						payReqMaps.put("CARDSALEPRC" , nTotCardDcfee);
						payReqMaps.put("REGID" , sMemberNo);
						payReqMaps.put("CARDTERMPRC" , sCardTermPrc);
						
						result = orderService.insertOrder(payReqMaps);
						System.out.println("*** insertOrder payReqMaps = " + payReqMaps);
						System.out.println("*** insertOrder result = " + result);
						
						if(result == 1){
							
							//회원은 cart테이블의 orderlist를 가져온다
							//비회원은 cookie의 ordrelist를 가져온다
							ArrayList<HashMap<String,Object>> orderList = new ArrayList<HashMap<String,Object>>();
							
							//회원처리
							if(!sMemberNo.equals("")) {
								String ol = (String) orderService.getCartOrderList(sMemberNo).get("CARTLIST");
								
								JSONArray jsonArray = JSONArray.fromObject(ol);
								System.out.println("jsonArray = " + jsonArray.size());
								
								for(int i=0; i<jsonArray.size();i++) {
									JSONObject jSonObject = (JSONObject) jsonArray.get(i);
									String aa = (String) jSonObject.get("a");
									String aaa[] = aa.split("_");
									
									HashMap<String, Object> map = new HashMap<String,Object>();
									map.put("prdcd", aaa[0]);
									map.put("sapcd", aaa[1]);
									map.put("buyqty", jSonObject.get("b"));
									
									orderList.add( map );
								}		
							} else {
							//비회원 처리 	
							}
							
							System.out.println("*** orderList = " + orderList);
							
							int i = 0;
							for(HashMap<String,Object> order : orderList) {
								try{
									SEQ = getMaxNumber("TBLORDERDETAIL.SEQ", true);
						        } catch (Exception e) {
						        	SEQ = 1;
						 			// TODO Auto-generated catch block
						 			e.printStackTrace();
						 		}
								
								  HashMap<String,Object> h = order;
						          
						          String sPrdCd = UtilBean.checkNullString(h.get("PRDCD")); // 상품코드
						          String sSapCd = UtilBean.checkNullString(h.get("SAPCD")); // SAP코드
						          String sQuantity = UtilBean.checkNullString(h.get("QUANTITY")); // 수량
						          /**************************************************************************************/
						          /** 배송비 추가 **/
						          /**************************************************************************************/
						          String sSumDeliFee = "";
						          String sCP1 = "";
						          String sCP2 = "";
						          String sCP3 = "";
						          String sUpPrdCd = "";
						          if (vDelifeeList != null && vDelifeeList.size() > 0) {
						            for (int k = 0; k < vDelifeeList.size(); k++) {
						              HashMap<String,Object> hData = (HashMap<String,Object>) vDelifeeList.get(k);
						              String[] aPrdData = UtilBean.split(UtilBean.checkNullString(hData.get("CPS")), "_"); // 업체코드_상품코드_SAP코드
						              String[] aCP = UtilBean.makeArray(UtilBean.checkNullString(hData.get("CP")), 4, "_"); // 업체코드 3 : 단일(상품별),2 : 동일(상품별),1 : 묶음
						              if (sPrdCd.equals(UtilBean.checkNullString(aPrdData[1])) && sSapCd.equals(UtilBean.checkNullString(aPrdData[2]))) {
						                sSumDeliFee = UtilBean.checkNullString(hData.get("SUMDELIFEE")); // 배송비
						                sUpPrdCd = UtilBean.checkNullString(UtilBean.checkNullString(hData.get("UPPRCD")));
						                sCP1 = UtilBean.checkNullStringR(aCP[1], "0");
						                sCP2 = UtilBean.checkNullStringR(aCP[2], "0");
						                sCP3 = UtilBean.checkNullStringR(aCP[3], "0");
						              }
						            }
						          }
						          
								String CORPNO = "a00001";
								String PRDCD = order.get("prdcd").toString();
								
								
								System.out.println("*** insert order for member -- OPTIONFL : " + order.get("OPTIONFL"));
								
								
								HashMap<String, String> itemView = new HashMap<String, String>();
						        itemView = itemService.getItemData(PRDCD);
								
						        
						        System.out.println("*** insert order for member -- itemView : " + itemView);
						        
						        
						        String PRDNM = UtilBean.checkNullString(itemView.get("PRDNM"));
								String SAPCD = "";
								
								String strORDQTY = "";
								if(itemView.get("ORDQTY") == null)	strORDQTY = "0";
								else strORDQTY = String.valueOf(itemView.get("ORDQTY"));
								strORDQTY = (String) order.get("buyqty");
								
								String ORDQTY = strORDQTY;		//상품별 구매수량

								
								String strSELPRC = "";
								if(itemView.get("SELPRC") == null)	strSELPRC = "0";
								else strSELPRC = String.valueOf(itemView.get("SELPRC"));
								
								String strSTTLPRC = "";
								if(itemView.get("PRICE") == null)	strSTTLPRC = "0";
								else strSTTLPRC = String.valueOf(itemView.get("PRICE"));
								
								String strPURPRC = "";
								if(itemView.get("PURPRC") == null)	strPURPRC = "0";
								else strPURPRC = String.valueOf(itemView.get("PURPRC"));
								
								String strBUYPRC = "";
								if(itemView.get("BUYPRC") == null)	strBUYPRC = "0";
								else strBUYPRC = String.valueOf(itemView.get("BUYPRC"));
								
								
								String strSUPPPRC = "";
								if(itemView.get("SUPPPRC") == null)	strSUPPPRC = "0";
								else strSUPPPRC = String.valueOf(itemView.get("SUPPPRC"));
								
								String strCMMS = "";
								if(itemView.get("CMMS") == null)	strCMMS = "0";
								else strCMMS = String.valueOf(itemView.get("CMMS"));
								
								
								int STTLPRC = Integer.parseInt(strSTTLPRC);
								int SELPRC = Integer.parseInt(strSELPRC);
								int PURPRC = Integer.parseInt(strPURPRC);
								int BUYPRC = Integer.parseInt(strBUYPRC);
								int SUPPPRC = Integer.parseInt(strSUPPPRC);
								
								int CMMS = Integer.parseInt(strCMMS);
								int USECPNPRC = 0;
								int USECASHPT = 0;
								int ACCUMCASHPT = 0;
								String USECPNCD = "";
								
								int DBLCPNPRC = 0;
								String INVNO = "";
								String INVNOGRNTDT = "";
								int DLVTMSNO = 0;
								String PRDKIND = UtilBean.checkNullString(itemView.get("OPTIONFL"));
								
								String DLVLOGICONM = "";
								String RWRDPRDNM = "";
								String INVNM = "";
								String REMARK1 = "";
								
								int CSTMNO = Integer.parseInt(sMemberNo);
								String DBLCPNCD = "";
								int USECPNSEQ = 0;
								int DBLCPNSEQ = 0;
								
								String PRDTYPE = "";
								String SNSDLVFL = "";
								String PRDNONM = "";
								String RWRDPRDID = "";
								String RWRDPRDCLCD = "";
								
								String POINTYN = "";
								String DELIFEE = "";
								String CP1 = "";
								String CP2 = "";
								String CP3 = "";
								
								String DELIFEEPB = "";
								String DELIUPPRDCD = "";
								String DLVSTDDT = "";
								
								
								
								payReqMaps = new HashMap<String,Object>();
								payReqMaps.put("ORDNO" , LGD_OID);
								payReqMaps.put("CORPNO" , CORPNO);
								payReqMaps.put("SEQ" , SEQ);
								payReqMaps.put("ORDSTATCD" , sOd);
								
								payReqMaps.put("PRDCD" , PRDCD);
								payReqMaps.put("PRDNM" , PRDNM);
								payReqMaps.put("SAPCD" , SAPCD);
								payReqMaps.put("ORDQTY" , ORDQTY);
								
								payReqMaps.put("STTLPRC" , STTLPRC);
								payReqMaps.put("SELPRC" , SELPRC);
								payReqMaps.put("PURPRC" , PURPRC);
								payReqMaps.put("BUYPRC" , BUYPRC);
								payReqMaps.put("SUPPPRC" , SUPPPRC);
								
								payReqMaps.put("CMMS" , CMMS);
								payReqMaps.put("USECPNPRC" , "");
								payReqMaps.put("USECASHPT" , "");
								payReqMaps.put("ACCUMCASHPT" , "");
								payReqMaps.put("USECPNCD" , "");
								
								payReqMaps.put("DBLCPNPRC" , "");
								payReqMaps.put("INVNO" , "");
								payReqMaps.put("INVNOGRNTDT" , "");
								payReqMaps.put("DLVTMSNO" , "");
								payReqMaps.put("PRDKIND" , PRDKIND);
								
								payReqMaps.put("DLVLOGICONM" , DLVLOGICONM);
								payReqMaps.put("RWRDPRDNM" , "");
								payReqMaps.put("INVNM" , INVNM);
								payReqMaps.put("REMARK1" , "");
								payReqMaps.put("REGID" , REGID);
								
								payReqMaps.put("CSTMNO" , CSTMNO);
								payReqMaps.put("DBLCPNCD" , "");
								payReqMaps.put("USECPNSEQ" , "");
								payReqMaps.put("DBLCPNSEQ" , "");
								
								payReqMaps.put("PRDTYPE" , PRDTYPE);
								payReqMaps.put("SNSDLVFL" , SNSDLVFL);
								payReqMaps.put("PRDNONM" , PRDNONM);
								payReqMaps.put("RWRDPRDID" , "");
								payReqMaps.put("RWRDPRDCLCD" , "");
								
								payReqMaps.put("POINTYN" , POINTYN);
								payReqMaps.put("DELIFEE" , DELIFEE);
								payReqMaps.put("CP1" , CP1);
								payReqMaps.put("CP2" , CP2);
								payReqMaps.put("CP3" , CP3);
								
								payReqMaps.put("DELIFEEPB" , "N");
								payReqMaps.put("DELIUPPRDCD" , DELIUPPRDCD);
								payReqMaps.put("DLVSTDDT" , DLVSTDDT);
										
								result = orderService.insertOrderDetail(payReqMaps);
								System.out.println("*** insertOrderDetail payReqMaps = " + payReqMaps);
								System.out.println("*** insertOrderDetail result = " + result);
								
								if(result == 1){
									//System.out.println("*** insert insertStock -- prdcd : " + sPrdCd + " -- sSapCd : " + sSapCd+ " -- sQuantity : " + sQuantity);
									
									try {
										//CommonUtil.insertStock("P", "SR01", sPrdCd, sSapCd, 0, 0, 0, sQuantity, "주문접수", UtilBean.convertToInt(sQuantity), true, "");
										
										isDBOK = true;
									} catch (Exception e) {
										e.printStackTrace();
										isDBOK = false;
									}
									
									
								}else{
									break;
								}
								i++;
							}
						}else{
							isDBOK = false;
						}
					}else{
						isDBOK = false;
					}
		        	 
					//##############2014-04-30 심윤 추가: 결제 DB저장
		         	            	
		         	//최종결제요청 결과 성공 DB처리 실패시 Rollback 처리
		         	 //DB처리 실패시 false로 변경해 주세요.
		         	if( !isDBOK ) {
		         		xpay.Rollback("상점 DB처리 실패로 인하여 Rollback 처리 [TID:" +xpay.Response("LGD_TID",0)+",MID:" + xpay.Response("LGD_MID",0)+",OID:"+xpay.Response("LGD_OID",0)+"]");
		         		
		         		System.out.println( "TX Rollback Response_code = " + xpay.Response("LGD_RESPCODE",0) + "<br>");
		         		System.out.println( "TX Rollback Response_msg = " + xpay.Response("LGD_RESPMSG",0) + "<p>");
		         		
		                 if( "0000".equals( xpay.m_szResCode ) ) {
		                	 System.out.println("자동취소가 정상적으로 완료 되었습니다.<br>");
		                 }else{
		                	 System.out.println("자동취소가 정상적으로 처리되지 않았습니다.<br>");
		                 }
		         	}
		         	
		         }else{
		         	//최종결제요청 결과 실패 DB처리
		        	 System.out.println("최종결제요청 결과 실패 DB처리하시기 바랍니다.<br>");          
		        	 
		        	 mv.addObject("rsltmsg", "상품결제요청 실패");
			    		mv.setViewName("redirect:/main.vh");
			    		return mv;
		         }
		     }else {
		         //2)API 요청실패 화면처리
		    	 System.out.println( "결제요청이 실패하였습니다.  <br>");
		    	 System.out.println( "TX 결제요청 Response_code = " + xpay.m_szResCode + "<br>");
		    	 System.out.println( "TX 결제요청 Response_msg = " + xpay.m_szResMsg + "<p>");
		         
		     	//최종결제요청 결과 실패 DB처리
		    	 System.out.println("최종결제요청 결과 실패 DB처리하시기 바랍니다.<br>");     
		    	 
		    	 mv.addObject("rsltmsg", "LG유플러스 제공 API를 사용할 수 없습니다");
	    		 mv.setViewName("redirect:/main.vh");
	    		 return mv;
		     }
		    
		     
		    //####### 2014-05-01 심윤 추가 : 주문완료
		    HashMap<String, String> orderCompleteList = new HashMap<String, String>();
			orderCompleteList = orderService.selectOrderComplete(orderno);		
			mv.addObject("orderCompleteList", orderCompleteList);
			
			//####### 2014-05-01 심윤 추가 : 주문완료
		
			mv.setViewName("orderComplete");	
			return mv;
		}
		
		
		public HashMap<String,Object> getProductCartList(Map<String, Object> paramMap) {
			
			String sInPrdCD = ""; // 상품코드
		    String sInSapCD = ""; // SAP코드
		    String sPurQty = ""; // 구매수량
		    String sSelPrc = ""; // 판매가
		    int nSelPrc = 0; // 상품금액
		    int nTotalSelPrc = 0; // 총상품금액
		    
			//ArrayList<HashMap<String,Object>> htReturn = new ArrayList<HashMap<String,Object>>();
			HashMap<String,Object> htReturn = new HashMap<String,Object>();
			HashMap<String,Object> htCartList = new HashMap<String,Object>();
			ArrayList<HashMap<String,String>> htPresentData = new ArrayList<HashMap<String,String>>();
			ArrayList<HashMap<String,String>> htDelifeeList = new ArrayList<HashMap<String,String>>();
			HashMap<String,String> htData = new HashMap<String,String>();
			HashMap<String,String> htData2 = new HashMap<String,String>();
		    
		    ArrayList<HashMap<String, String>> vList = new ArrayList<HashMap<String,String>>();
		    ArrayList<HashMap<String, String>> vCartList = new ArrayList<HashMap<String,String>>();
		    //Vector vCartList = new Vector();
		    String cstmno = paramMap.get("cstmno").toString();
		    String cstmrank = paramMap.get("cstmrank").toString();

		    HashMap<String,Object> paramMapCart = new HashMap<String,Object>();
			paramMapCart.put("cstmno", Long.valueOf(cstmno).longValue());
			paramMapCart.put("cstmrank", cstmrank);

		    htCartList = getProductCartComp(paramMapCart); 

		    if (htCartList != null) {
		    	vCartList = (ArrayList<HashMap<String, String>>) htCartList.get("vList"); // 장바구니 정보
		    }
		    if (vCartList != null && vCartList.size() > 0) {
		      for (int i = 0; i < vCartList.size(); i++) {
		        htData = vCartList.get(i);
		        
		        sInPrdCD += "'" + UtilBean.checkNullString(htData.get("INPRDCD")) + "'";
		        sInSapCD += "'" + UtilBean.checkNullString(htData.get("INSAPCD")) + "'";
		        if (i < vCartList.size() - 1) {
		          sInPrdCD += ",";
		          sInSapCD += ",";
		        }
		      }
		    }

		    /********************************************************************************************/
		    /** 일반회원접속인지 임직원/제휴회원접속여부 체크해서 쿠폰체크 **/
		    /********************************************************************************************/
		    String sSubStaff = UtilBean.substringCheckNull(cstmrank, 0, 4);
		    String sRank = "";
		    sSubStaff = UtilBean.substringCheckNull(cstmrank, 0, 4);
		    if (sSubStaff.equals("MG02") || sSubStaff.equals("MG03")) {
		      sRank = "Y";
		    } else {
		      sRank = "N";
		    }

			/********************************************************************************************/
		    /** 상품정보 **/
		    /** - PT01은 일반상품, PT02,PT03은 프로모션상품 **/
		    /** DLVMSPOL - 배송비정책구분(1:무료,2:조건별무료,3:유료) **/
		    /** DLVMSPMTCL - 선불후불(1:선불,2:후불) **/
		    /** DLVMSFSPRC - 얼마이상이면 **/
		    /** DLVMSIMPOPRC - 배송비 **/
		    /** FSDLVPOL - 무료배송과같이주문했는지 **/
		    /** PACKDLVPOL - 묶음배송정책(1:판매자상품묶음배송가능,2:동일제품만묶음배송가능,3:묶음배송불가상품) **/
		    /********************************************************************************************/
		    
		    if (vCartList != null && vCartList.size() > 0) {
		    	JSONArray jsonArray = JSONArray.fromObject(vCartList);
				System.out.println("jsonArray = " + jsonArray.size());
				
				ArrayList<HashMap<String, Object>> itemList_temp = new ArrayList<HashMap<String,Object>>();
				for(int i=0; i<jsonArray.size();i++) {
					JSONObject jSonObject = (JSONObject) jsonArray.get(i);
					String aa = (String) jSonObject.get("a");
					String aaa[] = aa.split("_");
					
					HashMap<String, Object> map = new HashMap<String,Object>();
					map.put("prdcd", aaa[0]);
					map.put("sapcd", aaa[1]);
					map.put("buyqty", jSonObject.get("b"));
					
					itemList_temp.add( map );
				}
				
		    	Map<String, Object> map = new HashMap<String, Object>();
				map.put("prdlist", itemList_temp);
		    	int totalCnt = 0;
				ArrayList<HashMap<String,String>> itemList = new ArrayList<HashMap<String,String>>();
				System.out.println("map = " + map + " / " + map.get("prdlist") );
				
				if(! map.get("prdlist").toString().equals("[]") ) {		
					vList = itemService.getItemList_prdlist(map);
					for(HashMap<String,String> item : itemList) {
						String prdimg1 = item.get("PRDIMG1");
						prdimg1 = CommonUtil.encodeURL(prdimg1, "utf-8");
						item.put("PRDIMG1_ENC", prdimg1);
						
						//주문갯수 찾기
						for(HashMap<String,Object> m : itemList_temp) {
							if(m.get("prdcd").equals(item.get("PRDCD"))) {
								item.put("BUYQTY", m.get("buyqty").toString() );
							}
						}
						
						totalCnt++;
					}
				}
		    	
		    }
		    /********************************************************************************************/
		    /** 상품정보에 장바구니 수량 추가 **/
		    /********************************************************************************************/
		    int tempCnt = 0;
		    String tempPrdNm = "";
		    if (vList != null && vList.size() > 0 && vCartList != null && vCartList.size() > 0) {
		      for (int i = 0; i < vList.size(); i++) {
		        htData = vList.get(i);
		        String sSapCd = UtilBean.checkNullString(htData.get("SAPCD"));
		        for (int j = 0; j < vCartList.size(); j++) {
		          htData2 = vCartList.get(j);
		          if (sSapCd.equals(UtilBean.checkNullString(htData2.get("INSAPCD")))) {
		            if (tempCnt == 0) {
		              tempPrdNm = UtilBean.checkNullString(UtilBean.checkNullString(htData.get("PRDNM")));
		            }
		            tempCnt++;
		            nSelPrc = UtilBean.convertToIntR(UtilBean.checkNullString((vList.get(i)).get("SELPRC")), 0); // 상품가격
		            (vList.get(i)).put("QUANTITY", UtilBean.checkNullString(htData2.get("INPURQTY"))); // 구매수량
		            (vList.get(i)).put("TOTALFEE", UtilBean.checkNullString(nSelPrc * UtilBean.convertToInt(UtilBean.checkNullString(htData2.get("INPURQTY"))))); // 구매수량 * 상품가격
		            (vList.get(i)).put("TAXEXEMPTPRC", UtilBean.checkNullString(UtilBean.convertToIntR(UtilBean.checkNullString((vList.get(i)).get("TAXEXEMPT")), 0) * UtilBean.convertToInt(UtilBean.checkNullString(htData2.get("INPURQTY"))))); // 구매수량 * 상품가격
		            nTotalSelPrc += nSelPrc * UtilBean.convertToInt(UtilBean.checkNullString(htData2.get("INPURQTY"))); // 총가격
		          }
		        }
		      }
		    }

		    String sOrder = (tempCnt - 1) == 0 ? " " : " 외 " + (tempCnt - 1) + "건";
		    htReturn.put("repPrdNm", "[ " + tempPrdNm + sOrder + "]");
		    //selectOrderGiftCoupon
		    htReturn.put("vList", vList);
		    htReturn.put("vCartList", vCartList);
		    htReturn.put("htPresentData", htPresentData);
		    htReturn.put("htDelifeeList", htDelifeeList);
		    htReturn.put("resultCartComp", htCartList.get("resultCartComp"));
		    htReturn.put("nInSelPrc", UtilBean.checkNullString(htCartList.get("nInSelPrc")));
		    htReturn.put("nSelPrc", UtilBean.checkNullString(htCartList.get("nSelPrc")));
		    return htReturn;
		}
		
		public HashMap<String,Object> getProductCartComp(Map<String, Object> paramMap) {
			HashMap<String,Object> htReturn = new HashMap<String,Object>();
			HashMap<String,Object> htDate = new HashMap<String,Object>();
			ArrayList<HashMap<String, Object>> vList = new ArrayList<HashMap<String, Object>>();
			JSONArray jSonArray = new JSONArray();
			
			String cstmno = paramMap.get("cstmno").toString();
		    String cstmrank = paramMap.get("cstmrank").toString();

			String sMNo = cstmno;
			String[] sCodeInfo; // 코드정보
			String sResult = "0";
			int idx = 1;
			int nInSelPrc = 0;
			int nSelPrc = 0;
			String sSignCl = "";
			/********************************************************************************************/
			/** 쿠키장바구니 상품정보 조회(비회원) **/
			/********************************************************************************************/
			if (sMNo.equals("")) {
				
			/********************************************************************************************/
			/** DB장바구니 상품정보 조회(회원) **/
			/********************************************************************************************/
			}else{
				HashMap<String,Object> cartList = new HashMap<String,Object>();
				cartList = orderService.getCartList(cstmno);
				
				if(cartList != null){
					if(!cartList.equals("")){
						jSonArray = (JSONArray) JSONValue.parse(UtilBean.decodeURL(UtilBean.checkNullString(cartList.get("ORDERLIST")), "utf-8"));
					}
				}
			}
			
			if (jSonArray != null && jSonArray.size() > 0) {
		      for (int i = 0; i < jSonArray.size(); i++) {
		        JSONObject jSonObject = (JSONObject) jSonArray.get(i);
		        sCodeInfo = UtilBean.split(UtilBean.checkNullString(jSonObject.get("a")), "_");
		        htDate = new HashMap<String,Object>();
		        htDate.put("INPRDCD", UtilBean.checkNullString(sCodeInfo[0]));
		        htDate.put("INSAPCD", UtilBean.checkNullString(sCodeInfo[1]));
		        htDate.put("INPURQTY", UtilBean.checkNullString(jSonObject.get("b")));
		        htDate.put("INSELPRC", UtilBean.checkNullString(jSonObject.get("c")));
		        htDate.put("CORPNO", UtilBean.checkNullString(jSonObject.get("d")));// 업체
		        vList.add(htDate);
		      }
		    }

			/*******************************************************************************/
		    /** 회원구분이 임직원이나 제휴일경우 쿠폰적용 **/
		    /*******************************************************************************/
		    String sSubStaff = sSubStaff = UtilBean.substringCheckNull(cstmrank, 0, 4);
		    String sRank = "";
		    if (sSubStaff.equals("MG02") || sSubStaff.equals("MG03")) {
		      sRank = "Y";
		    } else {
		      sRank = "N";
		    }
		    
		    /********************************************************************************************/
		    /** 장바구니 상품정보 비교 **/
		    /********************************************************************************************/
		    String sSelPrc = "";
		    String sInPurQty = "";
		    int nOrdCanStk = 0;
		      
		    String sSalstatcd = "";
		    
		    if (vList == null || vList.size() <= 0) { // 0 : 정상 1 : 장바구니물품오류 2 : 비정상금액 3 : 일시품절 4 : 판매중지 5 : 미승인상품
		    	sResult = "1"; // 장바구니가 비었을때
		    }
		    if (vList != null && vList.size() > 0) {
		    	for (int i = 0; i < vList.size(); i++) {
		    		HashMap<String,Object> htCartData = new HashMap<String,Object>();
		    		htCartData = (HashMap<String,Object>) vList.get(i);
		    		
		    		HashMap<String,Object> paramMapCart = new HashMap<String,Object>();
					paramMapCart.put("sMNo", Long.valueOf(cstmno).longValue());
					paramMapCart.put("sRank", cstmrank);
					paramMapCart.put("PRDCD", htCartData.get("INPRDCD"));
					paramMapCart.put("SAPCD", htCartData.get("INSAPCD"));
				    ArrayList<HashMap<String, Object>> orderCartList = new ArrayList<HashMap<String, Object>>();
				    orderCartList = orderService.selectOrderCart(paramMapCart);
				    
				    nInSelPrc = UtilBean.convertToInt(htCartData.get("INSELPRC"));
			          
			        sSalstatcd = UtilBean.checkNullString(htDate.get("SALSTATCD")); // 판매상태
			        nOrdCanStk = UtilBean.convertToInt(htDate.get("ORDCANSTK")); // 주문가능수량
			        sSelPrc = UtilBean.checkNullString(htDate.get("SELPRC")); // 판매가
			        nSelPrc = UtilBean.convertToInt(sSelPrc);
			        
			        String sCpnPrc = UtilBean.checkNullString(htDate.get("CPNPRC"));
			        String sSpSelPrcYn = UtilBean.checkNullString(htDate.get("SPSELPRCYN"));
			        sSignCl = UtilBean.checkNullString(htDate.get("SIGNCL"));
			        
			        if (nInSelPrc != nSelPrc) { // 금액변경
			        	sResult = "2";
			        	break;
			        } else if (sSalstatcd.equals("PS02") || UtilBean.convertToInt(sInPurQty) > nOrdCanStk) { // 일시품절
			        	sResult = "3";
			            break;
			        } else if (sSalstatcd.equals("PS03")) { // 판매중지()
			        	sResult = "4";
			            break;
			        } else if (!(sSignCl.equals("PA04") || sSignCl.equals("PA05") || sSignCl.equals("PA09") || sSignCl.equals("PA10") || sSignCl.equals("PA12") || sSignCl.equals("PA13"))) { // 승인된 상품체크(최초판매개시일이 있는지) PA04,05,09,10선노출, PA12승인완료, 프리패스PA13
			            sResult = "5";
			            break;
			        }
		    	}
		    }
		    
			htReturn.put("vList", vList);
			htReturn.put("resultCartComp", sResult);
			htReturn.put("nInSelPrc", nInSelPrc);
			htReturn.put("nSelPrc", nSelPrc);
			    
			return htReturn;
		}
		
		public HashMap<String,Object> getAmountCal(Map<String, Object> paramMap) {
		    HashMap<String,Object> htReturn = new HashMap<String,Object>();
		    HashMap<String,Object> htTotalPrice = new HashMap<String,Object>();
		    ArrayList<HashMap<String, Object>> vDelifeeList = new ArrayList<HashMap<String, Object>>(); // 배송리스트
		    
		    ArrayList<HashMap<String, String>> vList = new ArrayList<HashMap<String,String>>();
		    ArrayList<HashMap<String, String>> vCartList = new ArrayList<HashMap<String,String>>();
		    HashMap<String, Object> htData = new HashMap<String,Object>();
		    HashMap<String, String> htData2 = new HashMap<String,String>();
		    HashMap<String, String> htData3 = new HashMap<String,String>();

		    int idx = 1;
		    int nPrdCount = 0; // 상품 갯수
		    int nPrdTotalFee = 0; // 상품 총금액
		    int nTotalSettleFee = 0; // 최종 결제 금액
		    int nCpnMinusTotalFee = 0; // 차감된 쿠폰 총 금액
		    int nOrdUseCpnFee = 0; // 1차쿠폰금액
		    int nOrdDbCpnFee = 0; // 2차쿠폰금액
		    int nMinusPointTotalFee = 0; // 차감포인트
		    int nTotCardDcfee = 0; // 카드할인
		    int nTotDelifee = 0; // 배송료
		    int nPlusPointTotal = 0; // 적립할수있는금액
		    int nPlusPoint = 0; // 적립예정금
		    int nTotalTaxExemptPrc = 0; //총 면세금액
		    int nCpnTaxExemptPrc = 0; //쿠폰면세금액
		    int nTaxExemptPrc = 0;   //쿠폰적용안된 총면세금액
		    
		    String sCardCd = ""; // 신용카드 코드
		    String sCardRat = ""; // 신용카드할인율
		    String sCardTermPrc = ""; // 카드할인조건금액
		    
		    String cstmno = paramMap.get("cstmno").toString();
		    String cstmrank = paramMap.get("cstmrank").toString();
		    String sCpnUseYN = paramMap.get("sCpnUseYN").toString(); // 쿠폰사용여부
		    String[] aOrdUseCpnCd = (String[]) paramMap.get("ordUseCpnCd");
		    String[] aOrdDblCpnCd = (String[]) paramMap.get("ordDblCpnCd");
		    String point = paramMap.get("point").toString();
		    if(point == null) point = "0";
		    nMinusPointTotalFee = Integer.parseInt(point);		    

			String sMNo = cstmno;

		    if (htReturn != null) {
		      String sCartResult = UtilBean.checkNullString(htReturn.get("resultCartComp"));
		      vList = (ArrayList<HashMap<String, String>>) htReturn.get("vList"); // 상품리스트
		      vCartList = (ArrayList<HashMap<String, String>>) htReturn.get("vCartList"); // 장바구니리스트
		    }
		    if (vList != null && vList.size() > 0) {
		      for (int i = 0; i < vList.size(); i++) {
		    	htData3 = vList.get(i);
		        String sPointYn = UtilBean.checkNullString(htData3.get("POINTYN"));
		        String sVatCl = UtilBean.checkNullString(htData3.get("VATCL"));
		        String sPrdcd = UtilBean.checkNullString(htData3.get("PRDCD"));
		        
		        nPrdTotalFee += UtilBean.convertToInt(htData3.get("TOTALFEE"));
		        nPrdCount += UtilBean.convertToInt(htData3.get("QUANTITY"));
		        if (sVatCl.equals("TX02")) {
		          nTaxExemptPrc += UtilBean.convertToInt(htData3.get("TAXEXEMPTPRC"));
		        }
		      }
		    }

		    /********************************************************************************************/
		    /** 배송료 **/
		    /********************************************************************************************/
		    //DelifeeControlBean delifeeControlBean = new DelifeeControlBean();
		    //htDelifeeList = delifeeControlBean.getCartDelifeeList(vCartList); // 값을가져와서 비교해서 배송비를 담는다.
		    /*
		    if (htDelifeeList != null) {
		      vDelifeeList = (Vector) htDelifeeList.get("vDelifeeList"); // 배송료정책정보
		      nTotDelifee = UtilBean.convertToInt(UtilBean.checkNullStringR(htDelifeeList.get("TOTDELIFEE"), "0")); // 배송료 총합계
		    }
		    */

		    /********************************************************************************************/
		    /** 쿠폰사용시 차감 총액 및 쿠폰 사용 처리 **/
		    /********************************************************************************************/
		    ArrayList<HashMap<String, Object>> vCpnPrcList = new ArrayList<HashMap<String, Object>>();
		    if (UtilBean.checkNullString(sCpnUseYN).equals("Y")) {			    
		        if (aOrdUseCpnCd != null && aOrdUseCpnCd.length > 0) {
		          for (int i = 0; i < aOrdUseCpnCd.length; i++) {
		            String ordUseCpnCd[] = UtilBean.split(aOrdUseCpnCd[i], "|");
		            int nSeq = 1;
		            if (ordUseCpnCd != null && ordUseCpnCd.length > 0) {
		              
		              for (int j = 0; j < ordUseCpnCd.length; j++) {
		                int nCnpprc = 0;
		                String[] aCpnId = UtilBean.split(ordUseCpnCd[j], "_");
		                if (aCpnId != null && aCpnId.length > 0) {
		                  String sCpnId = UtilBean.checkNullString(aCpnId[0]);
		                  String sSapcd = UtilBean.checkNullString(aCpnId[1]);
		                  String sPrdcd = UtilBean.checkNullString(aCpnId[3]);
		                  int nSelprc = 0;
		                  
		                  htData.put("PRDCD", sPrdcd);
		                  htData.put("SAPCD", sSapcd);
		                  
		                  if(!sCpnId.equals("0")){
		                    idx = 1;
		                    
		                    HashMap<String, Object> h1 = new HashMap<String, Object>();
		                    h1 = orderService.getCouponType(aCpnId[0]);

		                    if(h1 != null && !UtilBean.checkNullString(h1.get("CPNCLCD")).equals("")){
		                      String sCpnclcd = UtilBean.checkNullString(h1.get("CPNCLCD"));
		                      ArrayList<HashMap<String, Object>> h = new ArrayList<HashMap<String, Object>>();
		                      HashMap<String,Object> paramMapCart = new HashMap<String,Object>();
		                      paramMapCart.put("CSTMNO", UtilBean.checkNullString(sMNo));
		                      paramMapCart.put("SEQ", UtilBean.checkNullString(aCpnId[2]));
		                      paramMapCart.put("PRDCD", UtilBean.checkNullString(sPrdcd));

		                      if(sCpnclcd.equals("CG02") || sCpnclcd.equals("CG03") || sCpnclcd.equals("CG04") || sCpnclcd.equals("CG07") || sCpnclcd.equals("CG08")){
		        			    h = orderService.getCouponApply23478(htData);
		                      }else if(sCpnclcd.equals("CG05") || sCpnclcd.equals("CG06") || sCpnclcd.equals("CG11") || sCpnclcd.equals("CG12") || sCpnclcd.equals("CG13")){
		                    	h = orderService.getCouponApply56111213(htData);
		                      }
		                      
		                      nOrdUseCpnFee += UtilBean.convertToInt(h.get(14));		//CNPPRC
		                      nCpnMinusTotalFee += UtilBean.convertToInt(h.get(14));	//CNPPRC
		                      nCpnTaxExemptPrc += UtilBean.convertToInt(h.get(15));		//TAXEXEMPTPRC
		                      nCnpprc = UtilBean.convertToInt(h.get(14));				//CNPPRC
		                      
		                      if( vList != null && vList.size() > 0){
		                        for(int k = 0 ; k < vList.size() ; k++){
		                          htData2 = vList.get(k);
		                          String sSapcd2 = UtilBean.checkNullString(htData2.get("SAPCD"));
		                          String sPrdcd2 = UtilBean.checkNullString(htData2.get("PRDCD"));
		                          
		                          if(sSapcd.equals(sSapcd2) && sPrdcd.equals(sPrdcd2)){
		                            nSelprc = UtilBean.convertToInt(UtilBean.checkNullString(htData2.get("SELPRC")))-nCnpprc;
		                          }
		                        }
		                      }
		                      
		                      htData.put("SELPRC", Integer.toString(nSelprc));
		                    }
		                    
		                  }else{
		                    if( vList != null && vList.size() > 0){
		                      for(int k = 0 ; k < vList.size() ; k++){
		                        htData2 = vList.get(k);
		                        String sSapcd2 = UtilBean.checkNullString(htData2.get("SAPCD"));
		                        String sPrdcd2 = UtilBean.checkNullString(htData2.get("PRDCD"));
		                        
		                        if(sSapcd.equals(sSapcd2) && sPrdcd.equals(sPrdcd2)){
		                          nSelprc = UtilBean.convertToInt(UtilBean.checkNullString(htData2.get("SELPRC")));
		                        }
		                      }
		                    }
		                    
		                    htData.put("SELPRC", Integer.toString(nSelprc));
		                  }
		                }
		                htData.put("SEQ", Integer.toString(nSeq++));
		                vCpnPrcList.add(htData);
		              }
		            }
		          }
		        }
		    	
		    }

		    if (aOrdDblCpnCd != null && aOrdDblCpnCd.length > 0) {
	          for (int i = 0; i < aOrdDblCpnCd.length; i++) {
	            String ordDblCpnCd[] = UtilBean.split(aOrdDblCpnCd[i], "|");
	            int nSeq = 1;
	            if (ordDblCpnCd != null && ordDblCpnCd.length > 0) {
	              for (int j = 0; j < ordDblCpnCd.length; j++) {
	                String[] aCpnId = UtilBean.split(ordDblCpnCd[j], "_");
	                if (aCpnId != null && aCpnId.length > 0) {
	                  String sCpnId = UtilBean.checkNullString(aCpnId[0]);
	                  String sSapcd = UtilBean.checkNullString(aCpnId[1]);
	                  String sPrdcd = UtilBean.checkNullString(aCpnId[3]);
	                  int nCpnprc = 0;
	                  int nTaxexemptprc = 0;
	                  if(!sCpnId.equals("0")){
	                	  ArrayList<HashMap<String, Object>> h = new ArrayList<HashMap<String, Object>>();
	                      HashMap<String,Object> paramMapCart = new HashMap<String,Object>();
	                      paramMapCart.put("CSTMNO", UtilBean.checkNullString(sMNo));
	                      paramMapCart.put("SEQ", UtilBean.checkNullString(aCpnId[2]));
	                      paramMapCart.put("PRDCD", UtilBean.checkNullString(sPrdcd));
	                      
	                      h = orderService.getCouponApply23478(htData);

	                    
	                    if(vCpnPrcList != null && vCpnPrcList.size() > 0){
	                      for(int k = 0 ; k < vCpnPrcList.size() ; k++){
	                        htData = vCpnPrcList.get(k);
	                        String sSapcd2 = UtilBean.checkNullString(htData.get("SAPCD"));
	                        String sPrdcd2 = UtilBean.checkNullString(htData.get("PRDCD"));
	                        int nSelprd2 = UtilBean.convertToIntR(UtilBean.checkNullString(htData.get("SELPRC")),0);
	                        int nSeq2 = UtilBean.convertToInt(UtilBean.checkNullString(htData.get("SEQ")));
	                        
	                        if(sSapcd.equals(sSapcd2) && sPrdcd.equals(sPrdcd2) && nSeq == nSeq2){
	                          int nDccl = UtilBean.convertToIntR(UtilBean.checkNullString(h.get(3)),0);		//DCCL
	                          int nDcrange = UtilBean.convertToIntR(UtilBean.checkNullString(h.get(4)),0);	//DCRANGE
	                          String sVatcl = UtilBean.checkNullString(h.get(16));							//VATCL
	                          
	                          if(nDccl == 1){
	                            nCpnprc = (int)Math.ceil((float)nSelprd2*(((float)nDcrange)/100));
	                          }else if(nDccl == 2){
	                            nCpnprc = nDcrange;
	                          }
	                          
	                          if(sVatcl.equals("TX02")){
	                            nTaxexemptprc = nCpnprc;
	                          }
	                          break;
	                        }
	                      }
	                    }
	                    
	                    nOrdDbCpnFee += nCpnprc;
	                    nCpnMinusTotalFee += nCpnprc;
	                    nCpnTaxExemptPrc += nTaxexemptprc;
	                    
	                  }
	                }
	                nSeq++;
	              }
	            }
	          }
	        }
		    /********************************************************************************************/
		    /** 총 실 결제 금액 **/
		    /********************************************************************************************/
		    nTotalTaxExemptPrc = nTaxExemptPrc - (nCpnTaxExemptPrc);
		    nTotalSettleFee = nPrdTotalFee; // 상품 총 금액
		    nTotalSettleFee -= nCpnMinusTotalFee; // 결제금액 쿠폰적용(-)
		    nTotalSettleFee -= nMinusPointTotalFee; // 결제금액 포인트적용(-)
		    nTotalSettleFee += nTotDelifee; // 결제금액 배송료(+)     
		    if(sCardCd != null){
		    	if(!sCardCd.equals("")){
				    ArrayList<HashMap<String, Object>> orderCardSale = new ArrayList<HashMap<String, Object>>();
		            HashMap<String,Object> paramMaps = new HashMap<String,Object>();
		            paramMaps.put("nTotalSettleFee", UtilBean.checkNullString(nTotalSettleFee));
		            paramMaps.put("sCardCd", UtilBean.checkNullString(sCardCd));
		            orderCardSale = orderService.getOrderCardSale(paramMaps);
		            
		            if(orderCardSale != null){
			            sCardRat = UtilBean.checkNullString(orderCardSale.get(3));	//DCRAT
			            sCardTermPrc = UtilBean.checkNullString(orderCardSale.get(2));	//CONPRC
			            nTotCardDcfee = (int) Math.ceil((nTotalSettleFee * ((double) UtilBean.convertToInt(orderCardSale.get(3)) / 100)));		//DCRAT
			            nTotalSettleFee -= nTotCardDcfee;
		            }
		    	}
		    }
            

		    htTotalPrice.put("nPrdCount", nPrdCount);
		    htTotalPrice.put("nPrdTotalFee", nPrdTotalFee);
		    htTotalPrice.put("nTotalSettleFee", nTotalSettleFee);
		    htTotalPrice.put("nCpnMinusTotalFee", nCpnMinusTotalFee);
		    htTotalPrice.put("nMinusPointTotalFee", nMinusPointTotalFee);
		    htTotalPrice.put("nTotCardDcfee", nTotCardDcfee);
		    htTotalPrice.put("nPlusPoint", nPlusPoint);
		    htTotalPrice.put("nDeliFee", nTotDelifee);
		    htTotalPrice.put("nOrdUseCpnFee", nOrdUseCpnFee);
		    htTotalPrice.put("nOrdDbCpnFee", nOrdDbCpnFee);
		    htTotalPrice.put("nTotalTaxExemptPrc", nTotalTaxExemptPrc);
		    
		    htTotalPrice.put("sCardCd", sCardCd);
		    htTotalPrice.put("sCardRat", sCardRat);
		    htTotalPrice.put("sCardTermPrc", sCardTermPrc);
		    
		    htTotalPrice.put("vDelifeeList", vDelifeeList);
		    return htTotalPrice;		    
		}
}
